feat: popup quảng cáo, đặt lại mật khẩu bằng token 80 ký tự, 2FA email, vá lỗ hổng bảo mật

- Popup/banner quảng cáo cấu hình từ admin (loại, link, lịch hiển thị)
- Đặt lại mật khẩu: token 80 ký tự kèm check digit Luhn thay cho token+email lộ trong URL, chỉ lưu bản băm, một lần dùng, hết hạn 60 phút
- Xác thực 2 lớp qua email khi đăng nhập (mã 6 số, ghi nhớ thiết bị 90 ngày)
- ApiAuthCheck chặn ngay tài khoản bị khoá dù JWT còn hạn (trước đây dùng được tới hết TTL)
- Handler trả 404 thay vì 500 khi ModelNotFoundException không bọc HttpException
- Test ClientTamperingTest: xác nhận IDOR/giả mạo dữ liệu từ client đều bị chặn

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
baodev0
2026-10-13 13:23:33 +07:00
co-authored by Claude Sonnet 5
parent e888a6ed5d
commit 12d5b4951c
33 changed files with 1499 additions and 51 deletions
+101
View File
@@ -0,0 +1,101 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Api\Admin;
use App\Models\PopupBanner;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Tests\TestCase;
class PopupBannerTest extends TestCase
{
use RefreshDatabase;
private function admin(): User
{
$role = Role::create(['name' => 'role-' . uniqid(), 'guard_name' => 'admin']);
$role->givePermissionTo(Permission::firstOrCreate(['name' => 'setting.manager', 'guard_name' => 'admin']));
$admin = User::factory()->create();
$admin->assignRole($role);
return $admin;
}
public function test_admin_creates_replaces_image_and_deletes_popup(): void
{
Storage::fake(PopupBanner::DISK);
$admin = $this->admin();
$id = $this->actingAs($admin, 'admin')
->post('/api/v1/administrator/popup-banners', [
'title' => 'Sale 11.11',
'type' => 'promotion',
'image' => UploadedFile::fake()->image('a.png'),
'link_url' => 'https://tgs.com.vn/khuyen-mai',
'open_in_new_tab' => '1',
], ['Accept' => 'application/json'])
->assertCreated()
->json('data.id');
$first = PopupBanner::findOrFail($id)->image_path;
Storage::disk(PopupBanner::DISK)->assertExists($first);
$this->actingAs($admin, 'admin')
->post("/api/v1/administrator/popup-banners/{$id}", [
'title' => 'Sale 12.12',
'type' => 'advertisement',
'image' => UploadedFile::fake()->image('b.png'),
], ['Accept' => 'application/json'])
->assertOk()
->assertJsonPath('data.type', 'advertisement')
->assertJsonPath('data.link_url', 'https://tgs.com.vn/khuyen-mai');
Storage::disk(PopupBanner::DISK)->assertMissing($first);
$second = PopupBanner::findOrFail($id)->image_path;
$this->actingAs($admin, 'admin')
->deleteJson("/api/v1/administrator/popup-banners/{$id}")
->assertOk();
Storage::disk(PopupBanner::DISK)->assertMissing($second);
$this->assertDatabaseMissing('popup_banners', ['id' => $id]);
}
public function test_rejects_unsafe_link_and_unknown_type(): void
{
Storage::fake(PopupBanner::DISK);
$this->actingAs($this->admin(), 'admin')
->post('/api/v1/administrator/popup-banners', [
'title' => 'X',
'type' => 'spam',
'image' => UploadedFile::fake()->image('a.png'),
'link_url' => 'javascript:alert(1)',
], ['Accept' => 'application/json'])
->assertStatus(422)
->assertJsonValidationErrors(['type', 'link_url']);
}
public function test_client_only_sees_active_popups_in_schedule(): void
{
$base = ['type' => 'advertisement', 'image_path' => 'popup-banners/x.png'];
PopupBanner::create($base + ['title' => 'Visible', 'link_url' => '/nap-tien']);
PopupBanner::create($base + ['title' => 'Off', 'is_active' => false]);
PopupBanner::create($base + ['title' => 'Future', 'starts_at' => now()->addDay()]);
PopupBanner::create($base + ['title' => 'Past', 'ends_at' => now()->subDay()]);
$this->withHeaders(['x-access-token' => $this->buildClientAccessToken()])
->getJson('/v1/setting/popups')
->assertOk()
->assertJsonCount(1, 'data')
->assertJsonPath('data.0.title', 'Visible')
->assertJsonPath('data.0.link_url', '/nap-tien')
->assertJsonMissingPath('data.0.image_path');
}
}
@@ -8,10 +8,10 @@ use App\Mail\Customer\PasswordResetLink;
use App\Models\Customer;
use App\Models\RefreshToken;
use App\Services\Api\Client\ClientAuthService;
use App\Support\PasswordResetToken;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
@@ -66,27 +66,80 @@ class ClientAuthSecurityTest extends TestCase
$this->api()->postJson('/v1/client/forgot-password', ['email' => strtoupper($customer->email)])->assertOk();
$this->assertSame($oldHash, $customer->fresh()->password);
Mail::assertQueued(PasswordResetLink::class, function (PasswordResetLink $mail) use ($customer) {
// Template seed bằng migration phải render được và chứa link reset, không chứa mật khẩu.
$token = null;
Mail::assertQueued(PasswordResetLink::class, function (PasswordResetLink $mail) use ($customer, &$token) {
$html = $mail->render();
preg_match('#/dat-lai-mat-khau\?t=([0-9a-z]+)#', $html, $match);
$token = $match[1] ?? null;
return $mail->hasTo($customer->email)
&& str_contains($html, '/dat-lai-mat-khau?token=')
&& !str_contains($html, 'email=')
&& str_contains($html, '60 phút');
});
$token = Password::broker('users')->createToken($customer);
$this->assertNotNull($token);
$this->assertSame(PasswordResetToken::LENGTH, strlen($token));
$this->assertTrue(PasswordResetToken::isWellFormed($token));
$this->api()->getJson('/v1/client/reset-password/' . $token)
->assertOk()
->assertJsonPath('data.email', $customer->email);
$this->api()->postJson('/v1/client/reset-password', [
'email' => $customer->email, 'token' => 'wrong', 'password' => 'NewPass123', 'password_confirmation' => 'NewPass123',
])->assertStatus(422);
$this->api()->postJson('/v1/client/reset-password', [
'email' => $customer->email, 'token' => $token, 'password' => 'NewPass123', 'password_confirmation' => 'NewPass123',
'token' => $token, 'password' => 'NewPass1234', 'password_confirmation' => 'NewPass1234',
])->assertOk();
$this->assertTrue(Hash::check('NewPass123', $customer->fresh()->password));
$this->assertTrue(Hash::check('NewPass1234', $customer->fresh()->password));
$this->assertSame(0, RefreshToken::where('customer_id', $customer->id)->count());
$this->api()->getJson('/v1/client/reset-password/' . $token)->assertNotFound();
$this->api()->postJson('/v1/client/reset-password', [
'token' => $token, 'password' => 'Other12345', 'password_confirmation' => 'Other12345',
])->assertStatus(422);
}
public function test_reset_token_rejects_tampered_unknown_expired_and_superseded_tokens(): void
{
$customer = Customer::factory()->create(['status' => 1]);
$token = PasswordResetToken::issue($customer);
$lastChar = $token[PasswordResetToken::LENGTH - 1];
$tampered = substr($token, 0, -1) . ($lastChar === 'a' ? 'b' : 'a');
$this->assertFalse(PasswordResetToken::isWellFormed($tampered));
$this->assertFalse(PasswordResetToken::isWellFormed(substr($token, 0, -1)));
$this->assertFalse(PasswordResetToken::isWellFormed(strtoupper($token)));
$this->api()->getJson('/v1/client/reset-password/' . $tampered)->assertNotFound();
$this->assertNull(PasswordResetToken::issue($customer), 'throttled within 60s');
$this->travel(61)->seconds();
$newer = PasswordResetToken::issue($customer);
$this->assertNotNull($newer);
$this->assertNull(PasswordResetToken::findCustomer($token), 'old link revoked when a new one is issued');
$this->assertSame($customer->id, PasswordResetToken::findCustomer($newer)?->id);
$other = Customer::factory()->create(['status' => 1]);
$otherToken = PasswordResetToken::issue($other);
$this->assertSame($other->id, PasswordResetToken::findCustomer($otherToken)?->id);
$this->travel(61)->minutes();
$this->assertNull(PasswordResetToken::findCustomer($newer), 'expired after 60 minutes');
$this->api()->postJson('/v1/client/reset-password', [
'token' => $newer, 'password' => 'NewPass1234', 'password_confirmation' => 'NewPass1234',
])->assertStatus(422);
}
public function test_locked_account_loses_api_access_even_with_unexpired_jwt(): void
{
$customer = Customer::factory()->create(['status' => 1]);
$token = \Tymon\JWTAuth\Facades\JWTAuth::fromUser($customer);
$this->api()->withHeaders(['Authorization' => "Bearer {$token}"])->getJson('/v1/client/me')->assertOk();
$customer->update(['status' => 3]);
$this->app['auth']->forgetGuards();
$this->api()->withHeaders(['Authorization' => "Bearer {$token}"])->getJson('/v1/client/me')->assertUnauthorized();
}
public function test_cccd_images_are_private_and_served_only_via_signed_url(): void
@@ -0,0 +1,206 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Api\Client;
use App\Enums\Invoice\InvoiceStatus;
use App\Models\Customer;
use App\Models\DnsDomain;
use App\Models\DnsManagerNS;
use App\Models\Invoice;
use App\Models\ModuleVmware;
use App\Models\Notification;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\ProductPricings;
use App\Models\Service;
use App\Models\Ticket;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\TestCase;
class ClientTamperingTest extends TestCase
{
use RefreshDatabase;
private Customer $victim;
private Customer $attacker;
private Order $order;
private Invoice $invoice;
private Service $hosting;
private Service $vps;
private ModuleVmware $vm;
private Product $product;
protected function setUp(): void
{
parent::setUp();
$this->victim = Customer::factory()->create(['status' => 1, 'total' => 500_000]);
$this->attacker = Customer::factory()->create(['status' => 1, 'total' => 10_000_000]);
$this->product = Product::factory()->create(['product_type' => 'hosting', 'is_active' => true]);
ProductPricings::create(['product_id' => $this->product->id, 'billing_cycle' => 'monthly', 'price' => 150_000, 'is_active' => true]);
$this->order = Order::create(['order_num' => 'ORD-VICTIM', 'customer_id' => $this->victim->id, 'total' => 150_000, 'status' => 0]);
$orderItem = OrderItem::create([
'order_id' => $this->order->id, 'product_id' => $this->product->id, 'billing_cycle' => 'monthly',
'months' => 1, 'quantity' => 1, 'price' => 150_000, 'addons_meta' => [],
]);
$this->invoice = Invoice::create([
'invoice_number' => 'INV-VICTIM', 'customer_id' => $this->victim->id, 'order_id' => $this->order->id,
'invoice_type' => 1, 'sub_total' => 150_000, 'tax' => 0, 'total' => 150_000,
'status' => InvoiceStatus::UNPAID->value,
]);
$this->hosting = Service::create([
'customer_id' => $this->victim->id, 'product_id' => $this->product->id, 'order_item_id' => $orderItem->id,
'type' => 'hosting', 'status' => 'active', 'started_at' => now()->subMonth(), 'expires_at' => now()->addDays(5),
]);
$this->vm = ModuleVmware::create(['customer_id' => $this->victim->id, 'vmware_id' => 987654]);
$this->vps = Service::create([
'customer_id' => $this->victim->id, 'product_id' => $this->product->id, 'type' => 'vps',
'status' => 'active', 'vm_id' => $this->vm->id, 'started_at' => now(), 'expires_at' => now()->addMonth(),
]);
}
private function as(Customer $customer): static
{
return $this->actingAs($customer, 'client')->withHeaders(['x-access-token' => $this->buildClientAccessToken()]);
}
private function assertDenied($response): void
{
$this->assertContains($response->status(), [403, 404, 422], "Expected denial, got {$response->status()}: " . $response->getContent());
}
public function test_profile_endpoints_ignore_balance_status_and_email_fields(): void
{
$payload = [
'fullname' => 'Attacker', 'phone' => '0900000000',
'credit' => 999_999_999, 'total' => 999_999_999, 'total_pending' => 0, 'point' => 999_999,
'status' => 1, 'email' => 'victim-takeover@example.com', 'two_factor_enabled' => false, 'id' => $this->victim->id,
];
$this->as($this->attacker)->putJson('/v1/client/update', $payload)->assertOk();
$this->as($this->attacker)->putJson('/v1/client/preferences', ['email_marketing' => true, 'receive_deposit' => true] + $payload)->assertOk();
$attacker = $this->attacker->fresh();
$this->assertSame(10_000_000, (int) $attacker->total);
$this->assertNotSame('victim-takeover@example.com', $attacker->email);
$this->assertSame('Attacker', $attacker->fullname);
$this->assertSame(500_000, (int) $this->victim->fresh()->total);
$this->assertNotSame('Attacker', $this->victim->fresh()->fullname);
}
public function test_cannot_read_another_customers_orders_invoices_or_transactions(): void
{
foreach ([
"/v1/client/orders/{$this->order->id}",
"/v1/client/orders/num/{$this->order->order_num}",
"/v1/client/invoices/{$this->invoice->id}",
"/v1/client/invoices/number/{$this->invoice->invoice_number}",
"/v1/client/invoices/order/{$this->order->order_num}",
"/v1/client/invoices/order/{$this->order->order_num}/pdf",
'/v1/client/payment-history/' . Str::uuid(),
] as $url) {
$this->assertDenied($this->as($this->attacker)->getJson($url));
}
}
public function test_cannot_pay_retry_or_renew_with_another_customers_resources(): void
{
$this->assertDenied($this->as($this->attacker)->postJson("/v1/client/invoices/number/{$this->invoice->invoice_number}/pay", ['payment_method' => 'balance']));
$this->assertDenied($this->as($this->attacker)->postJson("/v1/orders/{$this->order->order_num}/pay", ['payment_method' => 'balance']));
$this->assertDenied($this->as($this->attacker)->postJson("/v1/client/orders/{$this->order->id}/retry"));
$this->assertDenied($this->as($this->attacker)->postJson("/v1/client/dich-vu/{$this->hosting->id}/renew", ['months' => 1]));
$this->assertDenied($this->as($this->attacker)->patchJson("/v1/client/dich-vu/{$this->hosting->id}/auto-renew", ['auto_renew' => true]));
$this->assertDenied($this->as($this->attacker)->patchJson("/v1/client/client-service/{$this->hosting->uuid}/auto-renew", ['auto_renew' => true]));
$this->assertSame(InvoiceStatus::UNPAID->value, (int) $this->invoice->fresh()->status);
$this->assertSame(10_000_000, (int) $this->attacker->fresh()->total);
$this->assertSame(500_000, (int) $this->victim->fresh()->total);
$this->assertTrue($this->hosting->fresh()->expires_at->lt(now()->addDays(6)));
$this->assertFalse((bool) $this->hosting->fresh()->auto_renew);
}
public function test_cannot_view_or_operate_another_customers_vm_hosting_or_service(): void
{
foreach (["/v1/client/client-service/{$this->hosting->uuid}", "/v1/client/service/{$this->hosting->uuid}",
"/v1/client/client-service/{$this->vps->uuid}/available-os", "/v1/client/client-service/{$this->vps->uuid}/console-ticket"] as $url) {
$this->assertDenied($this->as($this->attacker)->getJson($url));
}
$this->assertDenied($this->as($this->attacker)->postJson("/v1/client/client-service/{$this->vps->uuid}/rebuild", ['os_id' => 1, 'password' => 'Secret12345!']));
foreach (['vm-power-off', 'vm-power-on', 'vm-restart', 'vm-change-password', 'vm-change-port', 'vm-change-ip', 'vm-create-snapshot', 'vm-rebuild', 'vm-upgrade-addons'] as $action) {
foreach ([$this->vm->id, $this->vm->vmware_id, $this->vps->uuid] as $id) {
$this->assertDenied($this->as($this->attacker)->postJson("/v1/system/{$action}", [
'product_id' => $id, 'id' => $id, 'vm_id' => $id, 'password' => 'Secret12345!', 'port' => 2222, 'name' => 'x',
]));
}
}
}
public function test_cannot_touch_another_customers_dns_zone(): void
{
$serverId = DB::table('dns_manager_servers')->insertGetId(['ip_address' => '10.0.0.1', 'password' => 'x']);
$zone = DnsDomain::create(['domain_name' => 'victim.vn', 'dns_manager_server_id' => $serverId, 'is_created' => 1]);
$zone->customer()->attach($this->victim->id);
$record = DnsManagerNS::create(['dns_manager_domain_id' => $zone->id, 'type' => 'A', 'type_valid' => 'A', 'name' => 'victim.vn', 'value' => '1.1.1.1', 'ttl' => 3600]);
$base = "/v1/client/client-service/domains/{$zone->id}";
$this->assertDenied($this->as($this->attacker)->getJson($base));
$this->assertDenied($this->as($this->attacker)->getJson("{$base}/records"));
$this->assertDenied($this->as($this->attacker)->postJson("{$base}/records", ['type' => 'A', 'name' => 'evil', 'value' => '6.6.6.6', 'ttl' => 300]));
$this->assertDenied($this->as($this->attacker)->putJson("{$base}/records/{$record->id}", ['type' => 'A', 'name' => 'victim.vn', 'value' => '6.6.6.6', 'ttl' => 300]));
$this->assertDenied($this->as($this->attacker)->deleteJson("{$base}/records/{$record->id}"));
$this->assertSame('1.1.1.1', $record->fresh()?->value);
$this->assertSame(1, DnsManagerNS::where('dns_manager_domain_id', $zone->id)->count());
}
public function test_cannot_read_reply_or_close_another_customers_ticket_or_notification(): void
{
$ticket = Ticket::create(['uuid' => (string) Str::uuid(), 'ticket_num' => 'TK-VICTIM', 'subject' => 'S', 'customer_id' => $this->victim->id, 'description' => 'D', 'status' => 'open']);
$notification = Notification::create(['recipient_type' => 'customer', 'recipient_id' => $this->victim->id, 'type' => 'info', 'title' => 'T', 'body' => 'B', 'is_read' => false]);
$this->assertDenied($this->as($this->attacker)->getJson("/v1/client/tickets/{$ticket->ticket_num}"));
$this->assertDenied($this->as($this->attacker)->postJson("/v1/client/tickets/{$ticket->ticket_num}/reply", ['message' => 'pwned', 'content' => 'pwned']));
$this->assertDenied($this->as($this->attacker)->patchJson("/v1/client/tickets/{$ticket->ticket_num}/close"));
$this->as($this->attacker)->patchJson("/v1/client/notifications/{$notification->id}/read");
$this->assertSame('open', $ticket->fresh()->status);
$this->assertFalse((bool) $notification->fresh()->is_read);
}
public function test_cannot_confirm_cancel_or_read_another_customers_deposit_code(): void
{
$uuid = $this->as($this->victim)->postJson('/v1/transaction/manual-deposit/prepare', ['amount' => 100_000, 'bank_id' => null])->json('data.uuid');
if (!$uuid) {
$this->markTestSkipped('prepare requires bank setup');
}
$this->assertDenied($this->as($this->attacker)->getJson("/v1/transaction/manual-deposit/{$uuid}"));
$this->assertDenied($this->as($this->attacker)->deleteJson("/v1/transaction/manual-deposit/{$uuid}/cancel"));
$this->assertDenied($this->as($this->attacker)->postJson('/v1/transaction/manual-deposit/confirm', ['uuid' => $uuid, 'proof_image' => 'deposit-proofs/x.png', 'amount' => 999_999_999]));
$this->assertSame(500_000, (int) $this->victim->fresh()->total);
}
public function test_order_price_is_computed_server_side_and_ignores_client_amounts(): void
{
$response = $this->as($this->attacker)->postJson('/v1/orders', [
'product_id' => $this->product->uuid, 'billing_cycle' => 'monthly', 'server_name' => 'attacker-site.vn',
'price' => 1, 'total' => 1, 'amount' => 1, 'sub_total' => 1, 'discount' => 999_999,
]);
$order = Order::where('customer_id', $this->attacker->id)->latest('id')->first();
$this->assertNotNull($order, 'order not created: ' . $response->getContent());
$this->assertSame(150_000, (int) $order->total);
}
}
@@ -0,0 +1,174 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Api\Client;
use App\Mail\Customer\TwoFactorCode;
use App\Models\Customer;
use App\Models\CustomerTrustedDevice;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Tests\TestCase;
class ClientTwoFactorTest extends TestCase
{
use RefreshDatabase;
private const PASSWORD = 'Secret12345';
private function api(): static
{
return $this->withHeaders(['x-access-token' => $this->buildClientAccessToken()]);
}
private function customer(bool $twoFactor = false): Customer
{
return Customer::factory()->create([
'status' => 1,
'password' => Hash::make(self::PASSWORD),
'two_factor_enabled' => $twoFactor,
]);
}
private function login(Customer $customer, ?string $deviceToken = null)
{
return $this->api()->postJson('/v1/client/login', array_filter([
'email' => $customer->email,
'password' => self::PASSWORD,
'device_token' => $deviceToken,
]));
}
private function lastCode(): string
{
$code = null;
Mail::assertQueued(TwoFactorCode::class, function (TwoFactorCode $mail) use (&$code) {
$code = $mail->data['code'];
return true;
});
return $code;
}
public function test_login_without_two_factor_returns_tokens_directly(): void
{
$this->login($this->customer())
->assertOk()
->assertJsonStructure(['data' => ['token', 'refresh_token']])
->assertJsonMissingPath('data.two_factor');
}
public function test_customer_enables_two_factor_with_emailed_code(): void
{
Mail::fake();
$customer = $this->customer();
$this->actingAs($customer, 'client')->api()->postJson('/v1/client/two-factor/setup-code')->assertOk();
$code = $this->lastCode();
$this->actingAs($customer, 'client')->api()
->postJson('/v1/client/two-factor/setup-code')
->assertStatus(422);
$this->actingAs($customer, 'client')->api()
->postJson('/v1/client/two-factor/enable', ['code' => $code === '000000' ? '111111' : '000000'])
->assertStatus(422);
$this->assertFalse($customer->fresh()->two_factor_enabled);
$this->actingAs($customer, 'client')->api()
->postJson('/v1/client/two-factor/enable', ['code' => $code])
->assertOk();
$this->assertTrue($customer->fresh()->two_factor_enabled);
$this->actingAs($customer->fresh(), 'client')->api()
->getJson('/v1/client/me')
->assertJsonPath('data.client.customer.active_2fa', 1);
}
public function test_login_requires_emailed_code_and_can_remember_device(): void
{
Mail::fake();
$customer = $this->customer(twoFactor: true);
$challenge = $this->login($customer)
->assertOk()
->assertJsonMissingPath('data.token')
->json('data.two_factor.challenge');
$this->assertSame(64, strlen($challenge));
$code = $this->lastCode();
$this->api()->postJson('/v1/client/login/two-factor', ['challenge' => $challenge, 'code' => $code === '000000' ? '111111' : '000000'])
->assertStatus(422);
$response = $this->api()->postJson('/v1/client/login/two-factor', [
'challenge' => $challenge, 'code' => $code, 'remember_device' => true,
])->assertOk()->assertJsonStructure(['data' => ['token', 'refresh_token', 'device_token', 'device_expires_in']]);
$this->api()->postJson('/v1/client/login/two-factor', ['challenge' => $challenge, 'code' => $code])
->assertStatus(422);
$deviceToken = $response->json('data.device_token');
$device = CustomerTrustedDevice::where('customer_id', $customer->id)->sole();
$this->assertNotSame($deviceToken, $device->token_hash);
$this->assertTrue($device->expires_at->between(now()->addDays(89), now()->addDays(91)));
$this->login($customer, $deviceToken)->assertOk()->assertJsonStructure(['data' => ['token']]);
$this->login($customer, str_repeat('x', 64))->assertOk()->assertJsonPath('data.two_factor.resend_in', 60);
$this->travel(91)->days();
$this->login($customer, $deviceToken)->assertOk()->assertJsonStructure(['data' => ['two_factor']]);
}
public function test_challenge_is_destroyed_after_five_wrong_codes(): void
{
Mail::fake();
$customer = $this->customer(twoFactor: true);
$challenge = $this->login($customer)->json('data.two_factor.challenge');
$code = $this->lastCode();
$wrong = $code === '000000' ? '111111' : '000000';
for ($i = 0; $i < 5; $i++) {
$this->api()->postJson('/v1/client/login/two-factor', ['challenge' => $challenge, 'code' => $wrong])->assertStatus(422);
}
$this->api()->postJson('/v1/client/login/two-factor', ['challenge' => $challenge, 'code' => $code])->assertStatus(429);
$this->travel(61)->seconds();
$this->api()->postJson('/v1/client/login/two-factor', ['challenge' => $challenge, 'code' => $code])
->assertStatus(422)
->assertJsonPath('errors.code.0', 'Phiên xác thực đã hết hạn, vui lòng đăng nhập lại.');
}
public function test_disabling_requires_password_and_revokes_devices_password_change_also_revokes(): void
{
$customer = $this->customer(twoFactor: true);
$twoFactor = app(\App\Services\Api\Client\ClientTwoFactorService::class);
$twoFactor->rememberDevice($customer, 'UA', '1.1.1.1');
$this->actingAs($customer, 'client')->api()->getJson('/v1/client/two-factor')
->assertOk()
->assertJsonPath('data.enabled', true)
->assertJsonCount(1, 'data.devices')
->assertJsonMissingPath('data.devices.0.token_hash');
$this->actingAs($customer, 'client')->api()
->postJson('/v1/client/two-factor/disable', ['password' => 'wrong-password'])
->assertStatus(422);
$this->assertTrue($customer->fresh()->two_factor_enabled);
$this->actingAs($customer, 'client')->api()
->postJson('/v1/client/two-factor/disable', ['password' => self::PASSWORD])
->assertOk();
$this->assertFalse($customer->fresh()->two_factor_enabled);
$this->assertSame(0, CustomerTrustedDevice::count());
$twoFactor->rememberDevice($customer, 'UA', '1.1.1.1');
$this->actingAs($customer, 'client')->api()->putJson('/v1/client/change-password', [
'current_password' => self::PASSWORD, 'password' => 'NewSecret123', 'password_confirmation' => 'NewSecret123',
])->assertOk();
$this->assertSame(0, CustomerTrustedDevice::count());
}
}