update rm deadcode

This commit is contained in:
baodev0
2026-09-27 11:42:40 +07:00
parent 82a71244ca
commit 3af59bd9c5
129 changed files with 5194 additions and 2698 deletions
@@ -0,0 +1,116 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Api\Admin\Employee;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Tests\TestCase;
class EmployeeRoleGuardTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
Permission::firstOrCreate(['name' => 'administrator.edit', 'guard_name' => 'admin']);
Permission::firstOrCreate(['name' => 'administrator.destroy', 'guard_name' => 'admin']);
Role::firstOrCreate(['name' => 'Full Administrator', 'guard_name' => 'admin']);
$administrator = Role::firstOrCreate(['name' => 'Administrator', 'guard_name' => 'admin']);
$sale = Role::firstOrCreate(['name' => 'Sale', 'guard_name' => 'admin']);
$administrator->givePermissionTo(['administrator.edit', 'administrator.destroy']);
$sale->givePermissionTo(['administrator.edit', 'administrator.destroy']);
}
private function makeEmployee(string $role): User
{
$user = User::factory()->create([
'username' => 'user-' . uniqid(),
'email' => uniqid() . '@example.com',
]);
$user->assignRole($role);
return $user;
}
private function payload(array $overrides = []): array
{
return array_merge([
'fullname' => 'Test User',
'username' => 'test-' . uniqid(),
'email' => uniqid() . '@example.com',
'role' => 'Sale',
], $overrides);
}
public function test_non_full_administrator_cannot_edit_a_full_administrator(): void
{
$fullAdmin = $this->makeEmployee('Full Administrator');
$caller = $this->makeEmployee('Administrator');
$response = $this->actingAs($caller, 'admin')->putJson(
"/api/v1/administrator/employees/{$fullAdmin->id}",
$this->payload(['role' => 'Sale']),
);
$response->assertStatus(403);
}
public function test_non_full_administrator_cannot_delete_a_full_administrator(): void
{
$fullAdmin = $this->makeEmployee('Full Administrator');
$caller = $this->makeEmployee('Administrator');
$response = $this->actingAs($caller, 'admin')->deleteJson(
"/api/v1/administrator/employees/{$fullAdmin->id}",
);
$response->assertStatus(403);
}
public function test_cannot_change_own_role(): void
{
$caller = $this->makeEmployee('Sale');
$response = $this->actingAs($caller, 'admin')->putJson(
"/api/v1/administrator/employees/{$caller->id}",
$this->payload(['username' => $caller->username, 'email' => $caller->email, 'role' => 'Administrator']),
);
$response->assertStatus(403);
}
public function test_non_full_administrator_cannot_assign_administrator_role(): void
{
$caller = $this->makeEmployee('Administrator');
$target = $this->makeEmployee('Sale');
$response = $this->actingAs($caller, 'admin')->putJson(
"/api/v1/administrator/employees/{$target->id}",
$this->payload(['username' => $target->username, 'email' => $target->email, 'role' => 'Administrator']),
);
$response->assertStatus(403);
}
public function test_full_administrator_can_assign_administrator_role(): void
{
$caller = $this->makeEmployee('Full Administrator');
$target = $this->makeEmployee('Sale');
$response = $this->actingAs($caller, 'admin')->putJson(
"/api/v1/administrator/employees/{$target->id}",
$this->payload(['username' => $target->username, 'email' => $target->email, 'role' => 'Administrator']),
);
$response->assertOk();
$this->assertTrue($target->fresh()->hasRole('Administrator'));
}
}
@@ -24,14 +24,14 @@ class LoginThrottleTest extends TestCase
{
for ($i = 0; $i < 5; $i++) {
$response = $this->postJson('/api/v1/administrator/login', [
'email' => 'nobody@example.com',
'username' => 'nobody',
'password' => 'wrong-password',
]);
$this->assertNotSame(429, $response->status());
}
$response = $this->postJson('/api/v1/administrator/login', [
'email' => 'nobody@example.com',
'username' => 'nobody',
'password' => 'wrong-password',
]);
@@ -62,9 +62,43 @@ class PermissionGatingTest extends TestCase
'tickets index' => ['GET', '/api/v1/administrator/tickets', 'support.view'],
'activity-logs index' => ['GET', '/api/v1/administrator/activity-logs', 'system-log.manager'],
'email-logs index' => ['GET', '/api/v1/administrator/email-logs', 'system-log.manager'],
'post-categories index' => ['GET', '/api/v1/administrator/post-categories', 'post.view'],
'posts index' => ['GET', '/api/v1/administrator/posts', 'post.view'],
'media index' => ['GET', '/api/v1/administrator/media', 'media.view'],
'dashboard stats' => ['GET', '/api/v1/administrator/dashboard/stats', 'dashboard.view'],
'queue jobs recent' => ['GET', '/api/v1/administrator/queue/jobs/recent', 'queue.manager'],
];
}
public function test_force_delete_post_requires_post_destroy_permission(): void
{
Permission::firstOrCreate(['name' => 'post.destroy', 'guard_name' => 'admin']);
$unauthorized = $this->makeAdminWithPermissions(['post.view']);
$this->actingAs($unauthorized, 'admin')
->deleteJson('/api/v1/administrator/posts/999/force-delete')
->assertStatus(403);
$authorized = $this->makeAdminWithPermissions(['post.destroy']);
$response = $this->actingAs($authorized, 'admin')
->deleteJson('/api/v1/administrator/posts/999/force-delete');
$this->assertNotSame(403, $response->status());
}
public function test_dashboard_requires_dashboard_view_permission(): void
{
Permission::firstOrCreate(['name' => 'dashboard.view', 'guard_name' => 'admin']);
$unauthorized = $this->makeAdminWithPermissions(['post.view']);
$this->actingAs($unauthorized, 'admin')
->getJson('/api/v1/administrator/dashboard/stats')
->assertStatus(403);
$authorized = $this->makeAdminWithPermissions(['dashboard.view']);
$response = $this->actingAs($authorized, 'admin')->getJson('/api/v1/administrator/dashboard/stats');
$this->assertNotSame(403, $response->status());
}
public function test_full_administrator_bypasses_all_permission_gates(): void
{
Role::firstOrCreate(['name' => 'Full Administrator', 'guard_name' => 'admin']);
@@ -7,6 +7,7 @@ namespace Tests\Feature\Api\Client;
use App\Mail\Customer\PasswordResetLink;
use App\Models\Customer;
use App\Models\RefreshToken;
use App\Services\Api\Client\ClientAuthService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
@@ -138,6 +139,76 @@ class ClientAuthSecurityTest extends TestCase
->getJson('/v1/banks')->assertStatus(429);
}
public function test_logout_revokes_refresh_token_so_it_cannot_be_used_again(): void
{
$customer = Customer::factory()->create(['status' => 1]);
$jwt = \Tymon\JWTAuth\Facades\JWTAuth::fromUser($customer);
$rawRefreshToken = 'raw-refresh-token';
RefreshToken::create([
'customer_id' => $customer->id,
'token' => hash('sha256', $rawRefreshToken),
'expires_at' => now()->addDays(30),
]);
$this->api()->withHeader('Authorization', "Bearer {$jwt}")
->postJson('/v1/client/logout', ['refresh_token' => $rawRefreshToken])
->assertOk();
$this->assertSame(0, RefreshToken::where('customer_id', $customer->id)->count());
$this->api()->postJson('/v1/client/refresh', ['refresh_token' => $rawRefreshToken])
->assertStatus(401);
}
public function test_reused_rotated_refresh_token_revokes_all_tokens_of_customer(): void
{
$customer = Customer::factory()->create(['status' => 1]);
$rawRefreshToken = 'raw-refresh-token';
RefreshToken::create([
'customer_id' => $customer->id,
'token' => hash('sha256', $rawRefreshToken),
'expires_at' => now()->addDays(30),
]);
// Rotation hợp lệ lần đầu: đánh dấu token cũ đã dùng, cấp token mới.
$first = $this->api()->postJson('/v1/client/refresh', ['refresh_token' => $rawRefreshToken])->assertOk();
$newRawRefreshToken = $first->json('data.refresh_token');
$this->assertNotSame($rawRefreshToken, $newRawRefreshToken);
// Token cũ vẫn còn nhưng đã đánh dấu revoked_at, cộng token mới vừa cấp.
$this->assertSame(2, RefreshToken::where('customer_id', $customer->id)->count());
$this->travel(ClientAuthService::REFRESH_TOKEN_REUSE_GRACE_SECONDS + 1)->seconds();
// Dùng lại token cũ (đã rotate): coi như bị lộ, thu hồi toàn bộ token của khách.
$this->api()->postJson('/v1/client/refresh', ['refresh_token' => $rawRefreshToken])
->assertStatus(401);
$this->assertSame(0, RefreshToken::where('customer_id', $customer->id)->count());
// Token mới (hợp lệ, chưa dùng) cũng đã bị thu hồi theo.
$this->api()->postJson('/v1/client/refresh', ['refresh_token' => $newRawRefreshToken])
->assertStatus(401);
}
public function test_concurrent_refresh_within_grace_window_does_not_revoke_sessions(): void
{
$customer = Customer::factory()->create(['status' => 1]);
$rawRefreshToken = 'raw-refresh-token';
RefreshToken::create([
'customer_id' => $customer->id,
'token' => hash('sha256', $rawRefreshToken),
'expires_at' => now()->addDays(30),
]);
$first = $this->api()->postJson('/v1/client/refresh', ['refresh_token' => $rawRefreshToken])->assertOk();
$second = $this->api()->postJson('/v1/client/refresh', ['refresh_token' => $rawRefreshToken])->assertOk();
foreach ([$first, $second] as $response) {
$this->api()->postJson('/v1/client/refresh', ['refresh_token' => $response->json('data.refresh_token')])
->assertOk();
}
}
public function test_legacy_cccd_path_is_not_exposed(): void
{
$customer = Customer::factory()->create(['status' => 1, 'front_identity_number' => '/uploads/2023/11/06/abc.jpg']);
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Api\Client;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Tests\TestCase;
class SecurityHardeningTest extends TestCase
{
use RefreshDatabase;
public function test_register_rejects_short_password(): void
{
$response = $this->withHeaders(['x-access-token' => $this->buildClientAccessToken()])->postJson('/v1/client/register', [
'fullname' => 'Nguyen Van A',
'phone' => '0912345678',
'email' => 'short-pass@example.com',
'password' => 'abc12345',
'password_confirmation' => 'abc12345',
]);
$response->assertStatus(422);
$response->assertJsonValidationErrors('password');
}
public function test_register_accepts_password_with_at_least_ten_characters(): void
{
$response = $this->withHeaders(['x-access-token' => $this->buildClientAccessToken()])->postJson('/v1/client/register', [
'fullname' => 'Nguyen Van B',
'phone' => '0912345679',
'email' => 'long-pass@example.com',
'password' => 'abcdefghij',
'password_confirmation' => 'abcdefghij',
]);
$response->assertJsonMissingValidationErrors('password');
}
public function test_cccd_upload_rejects_svg(): void
{
$customer = \App\Models\Customer::factory()->create();
$response = $this->actingAs($customer, 'client')
->withHeaders(['x-access-token' => $this->buildClientAccessToken()])
->post('/v1/client/update-cccd', [
'cmnd' => '012345678901',
'cmnd_before' => UploadedFile::fake()->create('front.svg', 10, 'image/svg+xml'),
'cmnd_after' => UploadedFile::fake()->image('back.jpg'),
]);
$response->assertStatus(422);
$response->assertJsonValidationErrors('cmnd_before');
}
}
@@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Api\Service;
use App\Enums\Order\OrderStatus;
use App\Models\Customer;
use App\Models\Order;
use App\Services\Api\Order\OrderService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class OrderErrorMessageTest extends TestCase
{
use RefreshDatabase;
private function actingAsCustomer(Customer $customer): static
{
return $this->actingAs($customer, 'client')
->withHeaders(['x-access-token' => $this->buildClientAccessToken()]);
}
public function test_pay_order_hides_unknown_exception_message(): void
{
$customer = Customer::factory()->create();
$order = Order::create([
'order_num' => 'ORD-TEST-' . uniqid(),
'customer_id' => $customer->id,
'sub_total' => 100000,
'discount_amount' => 0,
'total' => 100000,
'status' => OrderStatus::PENDING->value,
]);
$mock = \Mockery::mock(OrderService::class);
$mock->shouldReceive('pay')
->once()
->andThrow(new \RuntimeException('leaking internal DB connection string secret'));
$this->app->instance(OrderService::class, $mock);
$response = $this->actingAsCustomer($customer)->postJson("/v1/orders/{$order->order_num}/pay", [
'payment_method' => 'balance',
]);
$response->assertStatus(500);
$response->assertJsonPath('success', false);
$this->assertStringNotContainsString('leaking internal', (string) $response->getContent());
$this->assertSame('Có lỗi xảy ra, vui lòng thử lại', $response->json('message'));
}
public function test_pay_order_keeps_business_message_for_invalid_argument(): void
{
$customer = Customer::factory()->create(['total' => 0]);
$order = Order::create([
'order_num' => 'ORD-TEST-' . uniqid(),
'customer_id' => $customer->id,
'sub_total' => 100000,
'discount_amount' => 0,
'total' => 100000,
'status' => OrderStatus::PENDING->value,
]);
$response = $this->actingAsCustomer($customer)->postJson("/v1/orders/{$order->order_num}/pay", [
'payment_method' => 'balance',
]);
$response->assertStatus(422);
$response->assertJsonPath('success', false);
$this->assertStringContainsString('Số dư không đủ', (string) $response->json('message'));
}
}
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Tests\Feature\Api\Service;
use App\Enums\Invoice\InvoiceStatus;
use App\Models\Addon;
use App\Enums\Order\OrderStatus;
use App\Models\Customer;
use App\Models\Invoice;
@@ -13,6 +14,7 @@ use App\Models\OrderItem;
use App\Models\Product;
use App\Models\ProductPricings;
use App\Models\Service;
use App\Models\ServiceAddon;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
@@ -70,6 +72,137 @@ class RenewServiceTest extends TestCase
]);
}
private function createServiceWithCycle(string $billingCycle, int $cycleMonths, int $oldPrice): Service
{
$order = Order::create([
'order_num' => 'ORD-' . uniqid(),
'customer_id' => $this->customer->id,
'sub_total' => $oldPrice,
'total' => $oldPrice,
'status' => OrderStatus::ACTIVE->value,
]);
$orderItem = OrderItem::create([
'order_id' => $order->id,
'product_id' => $this->product->id,
'billing_cycle' => $billingCycle,
'months' => $cycleMonths,
'quantity' => 1,
'price' => $oldPrice,
]);
return Service::create([
'customer_id' => $this->customer->id,
'product_id' => $this->product->id,
'order_item_id' => $orderItem->id,
'status' => 'active',
'server_name' => 'test-server',
]);
}
public function test_renew_annual_service_for_exactly_one_cycle_charges_the_annual_price(): void
{
$service = $this->createServiceWithCycle('annually', 12, 1_800_000);
ProductPricings::create([
'product_id' => $this->product->id,
'billing_cycle' => 'annually',
'price' => 1_800_000,
'is_active' => true,
]);
$response = $this->actingAsCustomer()->postJson(
"/v1/client/dich-vu/{$service->id}/renew",
['months' => 12],
);
$response->assertOk();
$response->assertJsonPath('data.total', 1_800_000);
$this->assertDatabaseHas('invoices', [
'id' => $response->json('data.invoice_id'),
'total' => 1_800_000,
]);
}
public function test_renew_annual_service_with_months_not_matching_the_cycle_is_rejected(): void
{
$service = $this->createServiceWithCycle('annually', 12, 1_800_000);
ProductPricings::create([
'product_id' => $this->product->id,
'billing_cycle' => 'annually',
'price' => 1_800_000,
'is_active' => true,
]);
$response = $this->actingAsCustomer()->postJson(
"/v1/client/dich-vu/{$service->id}/renew",
['months' => 1],
);
$response->assertStatus(422);
$this->assertSame(0, Invoice::where('customer_id', $this->customer->id)->count());
}
public function test_renew_charges_the_recurring_addon_price_on_top_of_the_service_price(): void
{
$service = $this->createServiceWithOldPrice(90_000);
$addon = Addon::create([
'type' => $this->product->product_type,
'code' => 'ram',
'name' => 'RAM',
'price' => 50_000,
'min' => 1,
'max' => 64,
'step' => 1,
'status' => true,
]);
$service->orderItem->update(['addons_meta' => [[
'addon_id' => $addon->id,
'code' => 'ram',
'name' => 'RAM',
'qty' => 2,
'price' => 40_000,
'subtotal' => 80_000,
]]]);
ServiceAddon::create([
'service_id' => $service->id,
'addon_type' => 'ram',
'addon_value' => '6144',
'price' => 50_000,
]);
ProductPricings::create([
'product_id' => $this->product->id,
'billing_cycle' => 'monthly',
'price' => 100_000,
'is_active' => true,
]);
$response = $this->actingAsCustomer()->postJson(
"/v1/client/dich-vu/{$service->id}/renew",
['months' => 1],
);
$response->assertOk();
$response->assertJsonPath('data.total', 200_000);
$invoiceId = $response->json('data.invoice_id');
$this->assertDatabaseHas('invoice_items', [
'invoice_id' => $invoiceId,
'type' => 'renewal',
'unit_price' => 100_000,
]);
$this->assertDatabaseHas('invoice_items', [
'invoice_id' => $invoiceId,
'type' => 'addon',
'quantity' => 2,
'total_price' => 100_000,
]);
}
public function test_renew_uses_current_catalog_price_not_the_original_order_price(): void
{
$service = $this->createServiceWithOldPrice(90_000);
@@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Api\Service;
use App\Enums\Order\OrderStatus;
use App\Models\Customer;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\Service;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class ServiceOwnershipTest extends TestCase
{
use RefreshDatabase;
private function actingAsCustomer(Customer $customer): static
{
return $this->actingAs($customer, 'client')
->withHeaders(['x-access-token' => $this->buildClientAccessToken()]);
}
public function test_client_cannot_fetch_another_customers_service_by_uuid(): void
{
$owner = Customer::factory()->create();
$attacker = Customer::factory()->create();
$product = Product::factory()->create(['product_type' => 'hosting', 'is_active' => true]);
$order = Order::create([
'order_num' => 'ORD-' . uniqid(),
'customer_id' => $owner->id,
'sub_total' => 100000,
'total' => 100000,
'status' => OrderStatus::ACTIVE->value,
]);
$orderItem = OrderItem::create([
'order_id' => $order->id,
'product_id' => $product->id,
'billing_cycle' => 'monthly',
'months' => 1,
'quantity' => 1,
'price' => 100000,
]);
$service = Service::create([
'customer_id' => $owner->id,
'product_id' => $product->id,
'order_item_id' => $orderItem->id,
'status' => 'active',
'server_name' => 'owner-server',
]);
$response = $this->actingAsCustomer($attacker)->getJson("/v1/client/service/{$service->uuid}");
$response->assertStatus(404);
}
public function test_client_can_fetch_own_service_by_uuid(): void
{
$owner = Customer::factory()->create();
$product = Product::factory()->create(['product_type' => 'hosting', 'is_active' => true]);
$order = Order::create([
'order_num' => 'ORD-' . uniqid(),
'customer_id' => $owner->id,
'sub_total' => 100000,
'total' => 100000,
'status' => OrderStatus::ACTIVE->value,
]);
$orderItem = OrderItem::create([
'order_id' => $order->id,
'product_id' => $product->id,
'billing_cycle' => 'monthly',
'months' => 1,
'quantity' => 1,
'price' => 100000,
]);
$service = Service::create([
'customer_id' => $owner->id,
'product_id' => $product->id,
'order_item_id' => $orderItem->id,
'status' => 'active',
'server_name' => 'owner-server',
]);
$response = $this->actingAsCustomer($owner)->getJson("/v1/client/service/{$service->uuid}");
$this->assertNotSame(404, $response->status());
}
}
@@ -0,0 +1,139 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Api\Service;
use App\Models\Addon;
use App\Models\Customer;
use App\Models\Product;
use App\Models\ProductPricings;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class StoreOrderAddonTest extends TestCase
{
use RefreshDatabase;
private Customer $customer;
private Product $product;
protected function setUp(): void
{
parent::setUp();
$this->customer = Customer::factory()->create(['total' => 10_000_000]);
$this->product = Product::factory()->create([
'product_type' => 'vps',
'is_active' => true,
]);
ProductPricings::create([
'product_id' => $this->product->id,
'billing_cycle' => 'monthly',
'price' => 100_000,
'is_active' => true,
]);
}
private function actingAsCustomer(): static
{
return $this->actingAs($this->customer, 'client')
->withHeaders(['x-access-token' => $this->buildClientAccessToken()]);
}
private function storeOrder(array $addons): \Illuminate\Testing\TestResponse
{
return $this->actingAsCustomer()->postJson('/v1/orders', [
'product_id' => $this->product->uuid,
'billing_cycle' => 'monthly',
'addons' => $addons,
]);
}
public function test_addon_belonging_to_another_product_type_is_rejected(): void
{
$hostingAddon = Addon::create([
'type' => 'hosting',
'code' => 'storage',
'name' => 'Storage',
'min' => 1,
'max' => 100,
'step' => 1,
'price' => 10_000,
'status' => true,
]);
$response = $this->storeOrder([
['addon_id' => $hostingAddon->id, 'qty' => 1],
]);
$response->assertStatus(422)->assertJsonPath('success', false);
$this->assertSame(10_000_000, $this->customer->fresh()->total);
}
public function test_inactive_addon_is_rejected(): void
{
$inactiveAddon = Addon::create([
'type' => 'vps',
'code' => 'cpu-inactive',
'name' => 'CPU',
'min' => 1,
'max' => 32,
'step' => 1,
'price' => 25_000,
'status' => false,
]);
$response = $this->storeOrder([
['addon_id' => $inactiveAddon->id, 'qty' => 1],
]);
$response->assertStatus(422)->assertJsonPath('success', false);
}
public function test_qty_above_max_is_rejected(): void
{
$cpuAddon = Addon::create([
'type' => 'vps',
'code' => 'cpu',
'name' => 'CPU',
'min' => 1,
'max' => 32,
'step' => 1,
'price' => 25_000,
'status' => true,
]);
$response = $this->storeOrder([
['addon_id' => $cpuAddon->id, 'qty' => 999],
]);
$response->assertStatus(422)->assertJsonPath('success', false);
}
public function test_valid_addon_within_bounds_is_accepted(): void
{
$cpuAddon = Addon::create([
'type' => 'vps',
'code' => 'cpu-ok',
'name' => 'CPU',
'min' => 1,
'max' => 32,
'step' => 1,
'price' => 25_000,
'status' => true,
]);
$response = $this->storeOrder([
['addon_id' => $cpuAddon->id, 'qty' => 4],
]);
$response->assertStatus(201)->assertJsonPath('success', true);
$this->assertDatabaseHas('invoices', [
'customer_id' => $this->customer->id,
'total' => 100_000 + (25_000 * 4),
]);
}
}
@@ -0,0 +1,155 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Api\Service;
use App\Jobs\VirtualMachine\ChangeIpVMJob;
use App\Models\Customer;
use App\Models\IpPool;
use App\Models\ModuleIpAddress;
use App\Models\ModuleNetwork;
use App\Models\ModuleVmware;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Service;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Str;
use Tests\TestCase;
class VmChangeIpTest extends TestCase
{
use RefreshDatabase;
private function makeActiveServiceWithVm(string $status = 'active'): array
{
$customer = Customer::factory()->create();
$network = ModuleNetwork::create(['name' => 'test-net']);
$order = Order::create(['order_num' => 'ORD-' . Str::random(10), 'customer_id' => $customer->id]);
$orderItem = OrderItem::create(['order_id' => $order->id, 'server_name' => 'vm-test.local']);
$service = Service::create([
'customer_id' => $customer->id,
'order_item_id' => $orderItem->id,
'server_name' => 'vm-test.local',
'status' => $status,
]);
$currentIp = ModuleIpAddress::create([
'module_network_id' => $network->id,
'ip' => '103.1.1.10',
'status' => 1,
]);
$vm = ModuleVmware::create([
'name' => 'vm-test',
'customer_id' => $customer->id,
'vmware_id' => 'vm-9001',
'order_id' => $order->id,
'module_ip_address' => $currentIp->id,
'ip' => '103.1.1.10',
'status' => 1,
'service_id' => $service->id,
]);
IpPool::create([
'uuid' => (string) Str::uuid(),
'ip_address' => '103.1.1.10',
'module_network_id' => $network->id,
'status' => 'assigned',
'service_id' => $service->id,
]);
$freePool = IpPool::create([
'uuid' => (string) Str::uuid(),
'ip_address' => '103.1.1.20',
'module_network_id' => $network->id,
'status' => 'free',
'gateway' => '103.1.1.1',
]);
$service->refresh();
$service->update(['status' => $status]);
$otherCustomer = Customer::factory()->create();
$otherOrder = Order::create(['order_num' => 'ORD-' . Str::random(10), 'customer_id' => $otherCustomer->id]);
$otherService = Service::create([
'customer_id' => $otherCustomer->id,
'status' => 'active',
]);
$usedPool = IpPool::create([
'uuid' => (string) Str::uuid(),
'ip_address' => '103.1.1.30',
'module_network_id' => $network->id,
'status' => 'assigned',
'service_id' => $otherService->id,
]);
return compact('customer', 'network', 'service', 'vm', 'freePool', 'usedPool');
}
private function changeIpPayload(array $vars, string $ip): array
{
return [
'server_name' => $vars['service']->server_name,
'ip_address' => $ip,
'guest_user' => 'root',
'guest_password' => 'secret123',
];
}
public function test_change_ip_outside_pool_returns_422(): void
{
$vars = $this->makeActiveServiceWithVm();
$response = $this->actingAs($vars['customer'], 'client')
->withHeaders(['x-access-token' => $this->buildClientAccessToken()])
->postJson('/v1/system/vm-change-ip', $this->changeIpPayload($vars, '103.1.1.99'));
$response->assertStatus(422);
}
public function test_change_ip_already_in_use_returns_422(): void
{
$vars = $this->makeActiveServiceWithVm();
$response = $this->actingAs($vars['customer'], 'client')
->withHeaders(['x-access-token' => $this->buildClientAccessToken()])
->postJson('/v1/system/vm-change-ip', $this->changeIpPayload($vars, '103.1.1.30'));
$response->assertStatus(422);
}
public function test_change_ip_to_free_pool_ip_dispatches_job_with_pool_gateway(): void
{
Queue::fake();
$vars = $this->makeActiveServiceWithVm();
$response = $this->actingAs($vars['customer'], 'client')
->withHeaders(['x-access-token' => $this->buildClientAccessToken()])
->postJson('/v1/system/vm-change-ip', $this->changeIpPayload($vars, '103.1.1.20'));
$response->assertStatus(200)->assertJson(['success' => true]);
Queue::assertPushed(ChangeIpVMJob::class, function (ChangeIpVMJob $job) use ($vars) {
return $job->ipAddress === '103.1.1.20'
&& $job->gateway === '103.1.1.1'
&& $job->newIpPoolId === $vars['freePool']->id;
});
$this->assertSame('assigned', $vars['freePool']->fresh()->status);
}
public function test_power_on_for_suspended_service_returns_403(): void
{
$vars = $this->makeActiveServiceWithVm(status: 'suspended');
$response = $this->actingAs($vars['customer'], 'client')
->withHeaders(['x-access-token' => $this->buildClientAccessToken()])
->postJson('/v1/system/vm-power-on', ['product' => $vars['vm']->id]);
$response->assertStatus(403);
}
}
@@ -0,0 +1,160 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Api\Service;
use App\Enums\Invoice\InvoiceStatus;
use App\Jobs\VirtualMachine\Provision\UpdateVmConfigJob;
use App\Models\Addon;
use App\Models\Customer;
use App\Models\Invoice;
use App\Models\ModuleVmware;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\Service;
use App\Services\InvoicePaymentService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Bus;
use Tests\TestCase;
class VmUpgradeAddonsTest extends TestCase
{
use RefreshDatabase;
private Customer $customer;
private Product $product;
private Addon $cpuAddon;
private ModuleVmware $vm;
private Service $service;
private OrderItem $orderItem;
protected function setUp(): void
{
parent::setUp();
$this->customer = Customer::factory()->create(['total' => 10_000_000]);
$this->product = Product::factory()->create([
'product_type' => 'vps',
'is_active' => true,
'cpu' => 2,
'ram' => 2048,
'disk' => 40,
]);
$this->cpuAddon = Addon::create([
'type' => 'vps',
'code' => 'cpu',
'name' => 'CPU',
'min' => 1,
'max' => 8,
'step' => 1,
'price' => 50_000,
'status' => true,
]);
$order = Order::create([
'order_num' => 'ORD-UPG-TEST',
'customer_id' => $this->customer->id,
'total' => 100_000,
'status' => 1,
]);
$this->orderItem = OrderItem::create([
'order_id' => $order->id,
'product_id' => $this->product->id,
'billing_cycle' => 'monthly',
'months' => 1,
'quantity' => 1,
'price' => 100_000,
'addons_meta' => [],
]);
$this->vm = ModuleVmware::create([
'name' => 'upgrade-test-vm',
'customer_id' => $this->customer->id,
'order_id' => $order->id,
'vmware_id' => 'vm-upgrade-1',
'status' => 1,
]);
$this->service = Service::create([
'customer_id' => $this->customer->id,
'product_id' => $this->product->id,
'order_item_id' => $this->orderItem->id,
'vm_id' => $this->vm->id,
'status' => 'active',
'started_at' => now(),
'expires_at' => now()->addDays(15),
]);
}
private function actingAsCustomer(): static
{
return $this->actingAs($this->customer, 'client')
->withHeaders(['x-access-token' => $this->buildClientAccessToken()]);
}
public function test_upgrade_request_creates_unpaid_invoice_without_touching_vcenter(): void
{
Bus::fake();
$response = $this->actingAsCustomer()->postJson('/v1/system/vm-upgrade-addons', [
'product' => $this->vm->id,
'cpu' => 2,
]);
$response->assertStatus(200)->assertJsonPath('error', false);
$this->assertDatabaseHas('invoices', [
'customer_id' => $this->customer->id,
'service_id' => $this->service->id,
'invoice_type' => 3,
'status' => InvoiceStatus::UNPAID->value,
]);
$this->assertDatabaseHas('invoice_items', [
'addon_id' => $this->cpuAddon->id,
'type' => 'upgrade',
'quantity' => 2,
]);
Bus::assertNotDispatched(UpdateVmConfigJob::class);
}
public function test_qty_over_max_is_rejected(): void
{
$response = $this->actingAsCustomer()->postJson('/v1/system/vm-upgrade-addons', [
'product' => $this->vm->id,
'cpu' => 999,
]);
$response->assertStatus(422)->assertJsonPath('error', true);
$this->assertDatabaseCount('invoices', 0);
}
public function test_paying_the_invoice_dispatches_upgrade_job_and_updates_addons_meta(): void
{
$this->actingAsCustomer()->postJson('/v1/system/vm-upgrade-addons', [
'product' => $this->vm->id,
'cpu' => 2,
])->assertStatus(200);
$invoice = Invoice::where('service_id', $this->service->id)->firstOrFail();
Bus::fake();
app(InvoicePaymentService::class)->payWithBalance($invoice, $this->customer->fresh(), 'balance');
Bus::assertDispatched(UpdateVmConfigJob::class, function (UpdateVmConfigJob $job) {
return $job->moduleVmwareId === $this->vm->id
&& $job->cpuOverride === 4; // base 2 + purchased 2
});
$meta = $this->orderItem->fresh()->addons_meta;
$this->assertNotEmpty($meta);
$this->assertSame(2, (int) collect($meta)->firstWhere('addon_id', $this->cpuAddon->id)['qty']);
}
}
@@ -0,0 +1,142 @@
<?php
declare(strict_types=1);
namespace Tests\Feature\Api\Transaction;
use App\Enums\TransactionStatus;
use App\Models\Customer;
use App\Models\Transaction;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Tests\TestCase;
class ManualDepositProofTest extends TestCase
{
use RefreshDatabase;
private function actingAsCustomer(Customer $customer): static
{
return $this->actingAs($customer, 'client')
->withHeaders(['x-access-token' => $this->buildClientAccessToken()]);
}
public function test_confirm_rejects_proof_path_belonging_to_another_customer(): void
{
Storage::fake('local');
$owner = Customer::factory()->create();
$attacker = Customer::factory()->create();
$ownerPath = UploadedFile::fake()->image('proof.jpg')->store('deposit-proofs/' . $owner->id, 'local');
$transaction = Transaction::create([
'uuid' => Str::uuid()->toString(),
'public_code' => 'MAN-TEST-' . Str::random(6),
'trans' => 'MANTEST' . time(),
'amount' => 100000,
'customer_id' => $attacker->id,
'type' => 'manual',
'status' => TransactionStatus::PENDING->value,
]);
$response = $this->actingAsCustomer($attacker)->postJson('/v1/transaction/manual-deposit/confirm', [
'uuid' => $transaction->uuid,
'proof_image' => $ownerPath,
]);
$response->assertStatus(422)->assertJsonPath('error', true);
$this->assertNull($transaction->fresh()->proof_image);
}
public function test_confirm_rejects_traversal_and_reused_proof_paths(): void
{
Storage::fake('local');
$customer = Customer::factory()->create();
$other = Customer::factory()->create();
$otherPath = UploadedFile::fake()->image('proof.jpg')->store('deposit-proofs/' . $other->id, 'local');
$usedPath = UploadedFile::fake()->image('old.jpg')->store('deposit-proofs/' . $customer->id, 'local');
$newTransaction = fn () => Transaction::create([
'uuid' => Str::uuid()->toString(),
'public_code' => 'MAN-TEST-' . Str::random(6),
'trans' => 'MANTEST' . Str::random(8),
'amount' => 100000,
'customer_id' => $customer->id,
'type' => 'manual',
'status' => TransactionStatus::PENDING->value,
]);
$newTransaction()->update(['proof_image' => $usedPath, 'status' => TransactionStatus::COMPLETED->value]);
foreach (["deposit-proofs/{$customer->id}/../{$otherPath}", $usedPath] as $path) {
$transaction = $newTransaction();
$this->actingAsCustomer($customer)->postJson('/v1/transaction/manual-deposit/confirm', [
'uuid' => $transaction->uuid,
'proof_image' => $path,
])->assertStatus(422);
$this->assertNull($transaction->fresh()->proof_image);
}
}
public function test_confirm_without_proof_is_rejected(): void
{
$customer = Customer::factory()->create();
$transaction = Transaction::create([
'uuid' => Str::uuid()->toString(),
'public_code' => 'MAN-TEST-' . Str::random(6),
'trans' => 'MANTEST' . time(),
'amount' => 100000,
'customer_id' => $customer->id,
'type' => 'manual',
'status' => TransactionStatus::PENDING->value,
]);
$response = $this->actingAsCustomer($customer)->postJson('/v1/transaction/manual-deposit/confirm', [
'uuid' => $transaction->uuid,
]);
$response->assertStatus(422)->assertJsonPath('error', true);
}
public function test_upload_then_confirm_binds_proof_to_owner(): void
{
Storage::fake('local');
$customer = Customer::factory()->create();
$transaction = Transaction::create([
'uuid' => Str::uuid()->toString(),
'public_code' => 'MAN-TEST-' . Str::random(6),
'trans' => 'MANTEST' . time(),
'amount' => 100000,
'customer_id' => $customer->id,
'type' => 'manual',
'status' => TransactionStatus::PENDING->value,
]);
$upload = $this->actingAsCustomer($customer)->post('/v1/transaction/manual-deposit/upload-proof', [
'file' => UploadedFile::fake()->image('proof.jpg'),
]);
$upload->assertStatus(200);
$path = $upload->json('path');
$this->assertStringStartsWith('deposit-proofs/' . $customer->id . '/', $path);
Storage::disk('local')->assertExists($path);
$confirm = $this->actingAsCustomer($customer)->postJson('/v1/transaction/manual-deposit/confirm', [
'uuid' => $transaction->uuid,
'proof_image' => $path,
]);
$confirm->assertStatus(200)->assertJsonPath('error', false);
$this->assertSame($path, $transaction->fresh()->proof_image);
}
}