修复认证与基础安全链路

This commit is contained in:
2026-04-19 14:42:42 +08:00
parent bd97ed0b73
commit 5ce83a769d
13 changed files with 636 additions and 55 deletions
+104 -7
View File
@@ -1,5 +1,12 @@
<?php
/**
* 文件功能:前台认证控制器功能测试
*
* 覆盖登录即注册、老密码升级、封禁限制、退出登录、
* session 轮换与服务端限流等关键认证行为。
*/
namespace Tests\Feature;
use App\Models\Sysparam;
@@ -7,14 +14,21 @@ use App\Models\User;
use App\Models\UsernameBlacklist;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;
use Tests\TestCase;
/**
* 类功能:验证前台认证链路的核心行为。
*/
class AuthControllerTest extends TestCase
{
use RefreshDatabase;
/**
* 初始化验证码桩与基础系统参数。
*/
protected function setUp(): void
{
parent::setUp();
@@ -31,7 +45,37 @@ class AuthControllerTest extends TestCase
);
}
public function test_can_register_new_user()
/**
* 测试普通登录成功后会轮换 session id,阻断会话固定风险。
*/
public function test_login_regenerates_session_id(): void
{
Redis::shouldReceive('sismember')->with('banned_ips', '127.0.0.1')->andReturn(false);
$user = User::factory()->create([
'username' => 'session-user',
'password' => Hash::make('password123'),
]);
$this->startSession();
$oldSessionId = session()->getId();
$response = $this->postJson('/login', [
'username' => 'session-user',
'password' => 'password123',
'captcha' => '1234',
]);
$response->assertOk()
->assertJsonPath('status', 'success');
$this->assertAuthenticatedAs($user);
$this->assertNotSame($oldSessionId, session()->getId());
}
/**
* 验证首次登录的用户会被自动注册并完成登录。
*/
public function test_can_register_new_user(): void
{
Redis::shouldReceive('sismember')->with('banned_ips', '127.0.0.1')->andReturn(false);
@@ -54,7 +98,10 @@ class AuthControllerTest extends TestCase
$this->assertAuthenticated();
}
public function test_cannot_register_with_blacklisted_username()
/**
* 验证命中黑名单的用户名会被拒绝注册。
*/
public function test_cannot_register_with_blacklisted_username(): void
{
Redis::shouldReceive('sismember')->with('banned_ips', '127.0.0.1')->andReturn(false);
@@ -79,7 +126,10 @@ class AuthControllerTest extends TestCase
$this->assertGuest();
}
public function test_can_login_existing_user()
/**
* 验证已有用户可以通过正确密码登录。
*/
public function test_can_login_existing_user(): void
{
Redis::shouldReceive('sismember')->with('banned_ips', '127.0.0.1')->andReturn(false);
@@ -100,7 +150,10 @@ class AuthControllerTest extends TestCase
$this->assertAuthenticatedAs($user);
}
public function test_login_md5_user_upgrades_to_bcrypt()
/**
* 验证旧版 MD5 密码会在成功登录后升级为 bcrypt。
*/
public function test_login_md5_user_upgrades_to_bcrypt(): void
{
Redis::shouldReceive('sismember')->with('banned_ips', '127.0.0.1')->andReturn(false);
@@ -132,7 +185,10 @@ class AuthControllerTest extends TestCase
$this->assertAuthenticatedAs($user);
}
public function test_banned_user_cannot_login()
/**
* 验证被封禁账号无法登录。
*/
public function test_banned_user_cannot_login(): void
{
$user = User::factory()->create([
'username' => 'banneduser',
@@ -152,7 +208,10 @@ class AuthControllerTest extends TestCase
$this->assertGuest();
}
public function test_banned_ip_cannot_login()
/**
* 验证被封禁 IP 无法登录普通账号。
*/
public function test_banned_ip_cannot_login(): void
{
Redis::shouldReceive('sismember')->with('banned_ips', '127.0.0.1')->andReturn(true);
@@ -171,7 +230,10 @@ class AuthControllerTest extends TestCase
$this->assertGuest();
}
public function test_can_logout()
/**
* 验证已登录用户可以正常退出。
*/
public function test_can_logout(): void
{
/** @var \App\Models\User $user */
$user = User::factory()->create();
@@ -181,4 +243,39 @@ class AuthControllerTest extends TestCase
$response->assertRedirect('/');
$this->assertGuest();
}
/**
* 测试前台登录接口在连续失败后会触发服务端限流。
*/
public function test_login_route_is_rate_limited_after_repeated_failures(): void
{
RateLimiter::clear('chat-login|rate-user|127.0.0.1');
Redis::shouldReceive('sismember')->zeroOrMoreTimes()->andReturn(false);
User::factory()->create([
'username' => 'rate-user',
'password' => Hash::make('correct-password'),
]);
for ($attempt = 1; $attempt <= 5; $attempt++) {
$response = $this->withServerVariables(['REMOTE_ADDR' => '127.0.0.1'])
->postJson('/login', [
'username' => 'rate-user',
'password' => 'wrong-password',
'captcha' => '1234',
]);
$response->assertStatus(422);
}
$rateLimitedResponse = $this->withServerVariables(['REMOTE_ADDR' => '127.0.0.1'])
->postJson('/login', [
'username' => 'rate-user',
'password' => 'wrong-password',
'captcha' => '1234',
]);
$rateLimitedResponse->assertStatus(429)
->assertJsonPath('status', 'error');
}
}
@@ -16,6 +16,7 @@ namespace Tests\Feature\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Validator;
use Tests\TestCase;
@@ -112,4 +113,37 @@ class AdminAuthControllerTest extends TestCase
$response->assertRedirect(route('admin.dashboard'));
}
/**
* 测试隐藏后台登录入口会在连续失败后触发服务端限流。
*/
public function test_hidden_admin_login_route_is_rate_limited_after_repeated_failures(): void
{
RateLimiter::clear('admin-hidden-login|site-owner|127.0.0.1');
User::factory()->create([
'id' => 1,
'username' => 'site-owner',
'password' => Hash::make('correct-password'),
]);
for ($attempt = 1; $attempt <= 5; $attempt++) {
$response = $this->from('/lkddi')->post('/lkddi', [
'username' => 'site-owner',
'password' => 'wrong-password',
'captcha' => '1234',
]);
$response->assertRedirect('/lkddi');
}
$rateLimitedResponse = $this->from('/lkddi')->post('/lkddi', [
'username' => 'site-owner',
'password' => 'wrong-password',
'captcha' => '1234',
]);
$rateLimitedResponse->assertStatus(429);
$rateLimitedResponse->assertSessionHasErrors('username');
}
}
+224
View File
@@ -0,0 +1,224 @@
<?php
/**
* 文件功能:安全加固回归测试
*
* 覆盖可信代理 IP 解析、Banner 广播净化,以及 Horizon 访问门禁,
* 确保本轮安全修复不会在后续迭代中退化。
*
* @author ChatRoom Laravel
*
* @version 1.0.0
*/
namespace Tests\Feature;
use App\Events\BannerNotification;
use App\Http\Controllers\Admin\BannerBroadcastController;
use App\Http\Middleware\CloudflareProxies;
use App\Models\User;
use App\Providers\HorizonServiceProvider;
use Illuminate\Broadcasting\PendingBroadcast;
use Illuminate\Contracts\Broadcasting\Factory as BroadcastFactory;
use Illuminate\Foundation\Http\Middleware\ValidateCsrfToken;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\RateLimiter;
use Tests\TestCase;
/**
* 类功能:验证本轮安全修复的核心保护行为。
*/
class SecurityHardeningTest extends TestCase
{
/**
* 验证只有来自可信代理的请求才允许采用透传客户端 IP。
*/
public function test_cloudflare_proxies_only_accepts_forwarded_ip_from_trusted_proxy(): void
{
config()->set('app.trusted_proxies', ['127.0.0.1', '::1']);
$middleware = new CloudflareProxies;
$trustedRequest = Request::create('/rooms', 'GET', server: [
'REMOTE_ADDR' => '127.0.0.1',
'HTTP_CF_CONNECTING_IP' => '203.0.113.10',
]);
$middleware->handle($trustedRequest, fn () => response('ok'));
$this->assertSame('203.0.113.10', $trustedRequest->server->get('REMOTE_ADDR'));
$untrustedRequest = Request::create('/rooms', 'GET', server: [
'REMOTE_ADDR' => '198.51.100.25',
'HTTP_CF_CONNECTING_IP' => '203.0.113.11',
]);
$middleware->handle($untrustedRequest, fn () => response('ok'));
$this->assertSame('198.51.100.25', $untrustedRequest->server->get('REMOTE_ADDR'));
}
/**
* 验证 Banner 广播会将危险 HTML 净化为纯文本后再下发。
*/
public function test_banner_broadcast_sanitizes_user_controlled_html(): void
{
$fakeBroadcastFactory = new class
{
/**
* 记录控制器最终广播出去的事件对象。
*/
public ?BannerNotification $capturedEvent = null;
/**
* 截获 broadcast() helper 传入的事件实例。
*/
public function event($event): PendingBroadcast
{
$this->capturedEvent = $event;
return new class($event) extends PendingBroadcast
{
/**
* 构造一个不会二次派发的占位 PendingBroadcast。
*/
public function __construct(mixed $event)
{
parent::__construct(app('events'), $event);
}
/**
* 测试替身无需在析构时再次派发事件。
*/
public function __destruct() {}
};
}
/**
* 满足广播工厂抽象依赖,当前测试不会走到该分支。
*/
public function connection($name = null): never
{
throw new \RuntimeException('SecurityHardeningTest 不应调用广播连接。');
}
};
$this->app->instance(BroadcastFactory::class, $fakeBroadcastFactory);
$request = Request::create('/admin/banner/broadcast', 'POST', [
'target' => 'room',
'target_id' => 1,
'options' => [
'title' => '<span onclick="alert(1)">危险标题</span>',
'name' => '<b>管理员</b>',
'body' => '<span onclick="alert(1)">危险正文</span>',
'sub' => '<img src=x onerror=alert(1)>副标题',
'titleColor' => 'url(javascript:1)',
'gradient' => ['#123456', 'rgba(1,2,3,0.5)', 'url(javascript:alert(1))'],
'buttons' => [
[
'label' => '<b>立即处理</b>',
'color' => 'rgba(16,185,129,1)',
'action' => 'close',
],
],
],
]);
$request->headers->set('Accept', 'application/json');
$response = app(BannerBroadcastController::class)->send($request);
$this->assertSame(200, $response->getStatusCode());
$this->assertSame('success', $response->getData(true)['status']);
$this->assertInstanceOf(BannerNotification::class, $fakeBroadcastFactory->capturedEvent);
$this->assertSame('危险标题', $fakeBroadcastFactory->capturedEvent->options['title']);
$this->assertSame('管理员', $fakeBroadcastFactory->capturedEvent->options['name']);
$this->assertSame('危险正文', $fakeBroadcastFactory->capturedEvent->options['body']);
$this->assertSame('副标题', $fakeBroadcastFactory->capturedEvent->options['sub']);
$this->assertStringNotContainsString('"', $fakeBroadcastFactory->capturedEvent->options['titleColor']);
$this->assertStringNotContainsString('javascript', $fakeBroadcastFactory->capturedEvent->options['gradient'][2]);
$this->assertSame('立即处理', $fakeBroadcastFactory->capturedEvent->options['buttons'][0]['label']);
}
/**
* 验证 Horizon 面板仅允许站长账号访问。
*/
public function test_horizon_gate_only_allows_site_owner(): void
{
$provider = new class($this->app) extends HorizonServiceProvider
{
/**
* 显式注册测试所需的 Horizon gate。
*/
public function registerTestGate(): void
{
$this->gate();
}
};
$provider->registerTestGate();
$siteOwner = new User([
'username' => 'site-owner',
'user_level' => 1,
]);
$siteOwner->id = 1;
$revokedManager = new User([
'username' => 'revoked-manager',
'user_level' => 100,
]);
$this->assertTrue(Gate::forUser($siteOwner)->allows('viewHorizon'));
$this->assertFalse(Gate::forUser($revokedManager)->allows('viewHorizon'));
}
/**
* 验证前台登录入口在命中限流后会直接返回 429
*/
public function test_chat_login_route_returns_429_when_rate_limited(): void
{
$rateLimitKey = md5('chat-login'.'chat-login|testuser|127.0.0.1');
RateLimiter::clear($rateLimitKey);
foreach (range(1, 5) as $attempt) {
RateLimiter::hit($rateLimitKey, 60);
}
$response = $this->withoutMiddleware(ValidateCsrfToken::class)
->withServerVariables(['REMOTE_ADDR' => '127.0.0.1'])
->postJson('/login', [
'username' => 'TestUser',
'password' => 'secret',
'captcha' => 'invalid',
]);
$response->assertStatus(429)
->assertJsonPath('status', 'error');
RateLimiter::clear($rateLimitKey);
}
/**
* 验证隐藏后台登录入口在命中限流后会直接拒绝请求。
*/
public function test_hidden_admin_login_route_returns_429_when_rate_limited(): void
{
$rateLimitKey = md5('admin-hidden-login'.'admin-hidden-login|site-owner|127.0.0.1');
RateLimiter::clear($rateLimitKey);
foreach (range(1, 5) as $attempt) {
RateLimiter::hit($rateLimitKey, 60);
}
$response = $this->withoutMiddleware(ValidateCsrfToken::class)
->from('/lkddi')
->withServerVariables(['REMOTE_ADDR' => '127.0.0.1'])
->post('/lkddi', [
'username' => 'site-owner',
'password' => 'secret',
'captcha' => 'invalid',
]);
$response->assertStatus(429);
$this->assertStringContainsString('/lkddi', $response->headers->get('Location', ''));
RateLimiter::clear($rateLimitKey);
}
}