fix dashboard and apis
PHP Tests / php-tests (push) Failing after 9m1s

This commit is contained in:
Nyan Lin Paing
2026-08-16 23:50:39 +07:00
parent 60413bdebf
commit 8d74ac74cd
26 changed files with 638 additions and 55 deletions
@@ -3,7 +3,7 @@
use Illuminate\Support\Facades\Route;
use Modules\Booking\Http\Controllers\BookingController;
Route::prefix('api/v1')->middleware(['api', 'auth:sanctum', 'throttle:api-write'])->group(function () {
Route::prefix('api/v1')->middleware(['api', 'api.auth', 'throttle:api-write'])->group(function () {
Route::get('/bookings', [BookingController::class, 'index'])->name('booking.bookings.index');
Route::get('/bookings/{booking:booking_ref}', [BookingController::class, 'show'])->name('booking.bookings.show');
Route::post('/bookings', [BookingController::class, 'store'])->name('booking.bookings.store');
@@ -7,10 +7,29 @@ namespace Modules\Booking\Enums;
*/
enum BookingChannel: string
{
case MiniApp = 'mini_app';
case MiniApp = 'kbz_miniapp';
case Android = 'android';
case Ios = 'ios';
case Web = 'web';
case Agent = 'agent';
case Admin = 'admin';
/**
* Resolve the client's channel from its `Device-Type` header, defaulting
* to MiniApp when the header is missing or unrecognized. Agent/Admin are
* deliberately excluded from what a header can select those two are
* derived from how the request authenticated (FastAPI JWT, Filament),
* never a client-supplied value, so a customer can't spoof one via the
* header.
*/
public static function fromDeviceTypeHeader(?string $deviceType): self
{
$channel = self::tryFrom((string) $deviceType);
if ($channel === null || in_array($channel, [self::Agent, self::Admin], true)) {
return self::MiniApp;
}
return $channel;
}
}
@@ -31,10 +31,21 @@ class BookingController extends Controller
public function index(Request $request): AnonymousResourceCollection
{
Gate::authorize('viewAny', Booking::class);
$openid = $request->attributes->get('fastapi_openid');
$bookings = Booking::query()
->where('user_id', $request->user()->id)
$query = Booking::query();
if ($openid !== null) {
// FastAPI agent (JWT auth, no Laravel user) — scoped to the
// verified token's own openid, never a client-supplied value,
// so one agent session can't list another customer's bookings.
$query->where('openid', $openid);
} else {
Gate::authorize('viewAny', Booking::class);
$query->where('user_id', $request->user()->id);
}
$bookings = $query
->with(self::EAGER_LOADS)
->latest()
->paginate();
@@ -42,9 +53,15 @@ class BookingController extends Controller
return BookingResource::collection($bookings);
}
public function show(Booking $booking): BookingResource
public function show(Request $request, Booking $booking): BookingResource
{
Gate::authorize('view', $booking);
$openid = $request->attributes->get('fastapi_openid');
if ($openid !== null) {
abort_if($booking->openid !== $openid, 404);
} else {
Gate::authorize('view', $booking);
}
return new BookingResource($booking->load(self::EAGER_LOADS));
}
@@ -52,6 +69,11 @@ class BookingController extends Controller
public function store(StoreBookingRequest $request): JsonResponse
{
$validated = $request->validated();
$openid = $request->attributes->get('fastapi_openid');
if ($openid === null) {
Gate::authorize('create', Booking::class);
}
$selections = array_map(
fn (array $selection) => new VehicleSelectionData(
@@ -61,6 +83,14 @@ class BookingController extends Controller
$validated['selections'],
);
// The agent's own auth path always wins over anything a header could
// claim; customer channels come from Device-Type, not a
// client-supplied body field (BookingChannel::fromDeviceTypeHeader
// already refuses to hand back Agent/Admin from a header value).
$channel = $openid !== null
? BookingChannel::Agent
: BookingChannel::fromDeviceTypeHeader($request->header('Device-Type'));
$booking = $this->createBookingAction->handle(new CreateBookingData(
evRouteId: $validated['ev_route_id'],
departureTimeSlotId: $validated['departure_time_slot_id'],
@@ -70,11 +100,12 @@ class BookingController extends Controller
passengerPhone: $validated['passenger_phone'],
pickupAddress: $validated['pickup_address'],
dropoffAddress: $validated['dropoff_address'],
createdByChannel: isset($validated['created_by_channel'])
? BookingChannel::from($validated['created_by_channel'])
: BookingChannel::MiniApp,
createdByChannel: $channel,
// A verified FastAPI JWT's own openid always wins over a
// client-supplied one — a request can never claim a different
// customer's identity than its own token proves.
userId: $request->user()?->id,
openid: $validated['openid'] ?? null,
openid: $openid ?? $validated['openid'] ?? null,
pickupLat: $validated['pickup_lat'] ?? null,
pickupLng: $validated['pickup_lng'] ?? null,
dropoffLat: $validated['dropoff_lat'] ?? null,
@@ -4,7 +4,6 @@ namespace Modules\Booking\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Modules\Booking\Enums\BookingChannel;
use Modules\Shared\Enums\VehicleOption;
/**
@@ -41,11 +40,8 @@ class StoreBookingRequest extends FormRequest
'dropoff_address' => ['required', 'string', 'max:500'],
'dropoff_lat' => ['nullable', 'numeric', 'between:-90,90'],
'dropoff_lng' => ['nullable', 'numeric', 'between:-180,180'],
'openid' => ['nullable', 'string', 'max:255'],
'is_round_trip' => ['sometimes', 'boolean'],
'return_travel_date' => ['nullable', 'date', 'required_if:is_round_trip,true'],
// Admin-created bookings go through the Filament resource (T4.7), not this API.
'created_by_channel' => ['sometimes', Rule::enum(BookingChannel::class)->except(BookingChannel::Admin)],
];
}
}
@@ -1,6 +1,7 @@
<?php
use App\Models\User;
use Modules\Booking\Enums\BookingChannel;
use Modules\Booking\Enums\BookingStatus;
use Modules\Booking\Models\Booking;
use Modules\Catalog\Models\DepartureTimeSlot;
@@ -176,3 +177,47 @@ test('shape validation rejects an empty selections array', function () {
->assertStatus(422)
->assertJsonValidationErrors(['selections']);
});
test('created_by_channel defaults to kbz_miniapp when no Device-Type header is sent', function () {
[$route, $timeSlot] = bookableRouteAndSlot([[VehicleOption::BackSeat, '15000.00']]);
$this->withHeader('Authorization', "Bearer {$this->token}")
->postJson('/api/v1/bookings', bookingPayload($route, $timeSlot, [
['vehicle_option' => 'back_seat', 'passenger_count' => 1],
]))
->assertCreated()
->assertJsonPath('data.created_by_channel', BookingChannel::MiniApp->value);
});
test('created_by_channel is taken from the Device-Type header', function (string $deviceType, BookingChannel $expected) {
[$route, $timeSlot] = bookableRouteAndSlot([[VehicleOption::BackSeat, '15000.00']]);
$this->withHeader('Authorization', "Bearer {$this->token}")
->withHeader('Device-Type', $deviceType)
->postJson('/api/v1/bookings', bookingPayload($route, $timeSlot, [
['vehicle_option' => 'back_seat', 'passenger_count' => 1],
]))
->assertCreated()
->assertJsonPath('data.created_by_channel', $expected->value);
})->with([
'android' => ['android', BookingChannel::Android],
'ios' => ['ios', BookingChannel::Ios],
'web' => ['web', BookingChannel::Web],
'kbz_miniapp' => ['kbz_miniapp', BookingChannel::MiniApp],
]);
test('a Device-Type header cannot spoof the agent or admin channel', function (string $deviceType) {
[$route, $timeSlot] = bookableRouteAndSlot([[VehicleOption::BackSeat, '15000.00']]);
$this->withHeader('Authorization', "Bearer {$this->token}")
->withHeader('Device-Type', $deviceType)
->postJson('/api/v1/bookings', bookingPayload($route, $timeSlot, [
['vehicle_option' => 'back_seat', 'passenger_count' => 1],
]))
->assertCreated()
->assertJsonPath('data.created_by_channel', BookingChannel::MiniApp->value);
})->with([
'agent' => ['agent'],
'admin' => ['admin'],
'unrecognized value' => ['smart-fridge'],
]);
@@ -0,0 +1,86 @@
<?php
use Firebase\JWT\JWT;
use Modules\Booking\Enums\BookingChannel;
use Modules\Booking\Models\Booking;
use Modules\Catalog\Models\DepartureTimeSlot;
use Modules\Routing\Models\EvRoute;
use Modules\Routing\Models\RoutePricing;
use Modules\Shared\Enums\VehicleOption;
beforeEach(function () {
config(['services.fastapi_agent.jwt_secret' => 'test-fastapi-agent-secret-0123456789ABCDEF']);
config(['services.fastapi_agent.jwt_algorithm' => 'HS256']);
});
function fastApiAgentToken(string $openid): string
{
return JWT::encode([
'sub' => $openid,
'iat' => time(),
'exp' => time() + 3600,
], 'test-fastapi-agent-secret-0123456789ABCDEF', 'HS256');
}
test('a FastAPI JWT booking is stored against the verified openid, ignoring a spoofed body value', function () {
config(['booking.back_seat_enabled' => true]);
$route = EvRoute::factory()->create(['is_active' => true]);
$timeSlot = DepartureTimeSlot::factory()->create();
$route->timeSlots()->attach($timeSlot->id, ['is_active' => true]);
RoutePricing::factory()->create([
'ev_route_id' => $route->id,
'vehicle_option' => VehicleOption::BackSeat,
'price' => '15000.00',
]);
$token = fastApiAgentToken('real-customer-openid');
$this->withHeader('Authorization', "Bearer {$token}")
->withHeader('Device-Type', 'android') // the agent's own channel always wins, ignored here.
->postJson('/api/v1/bookings', [
'ev_route_id' => $route->id,
'departure_time_slot_id' => $timeSlot->id,
'travel_date' => now()->addDay()->toDateString(),
'selections' => [['vehicle_option' => 'back_seat', 'passenger_count' => 1]],
'passenger_name' => 'Jane Doe',
'passenger_phone' => '+959123456789',
'pickup_address' => '123 Pickup St',
'dropoff_address' => '456 Dropoff Ave',
'openid' => 'spoofed-openid',
])
->assertCreated();
$booking = Booking::sole();
expect($booking->openid)->toBe('real-customer-openid')
->and($booking->user_id)->toBeNull()
->and($booking->created_by_channel)->toBe(BookingChannel::Agent);
});
test('a FastAPI JWT can list and show only its own openid\'s bookings', function () {
$mine = Booking::factory()->create(['openid' => 'agent-openid-mine']);
Booking::factory()->create(['openid' => 'agent-openid-someone-else']);
$token = fastApiAgentToken('agent-openid-mine');
$this->withHeader('Authorization', "Bearer {$token}")
->getJson('/api/v1/bookings')
->assertSuccessful()
->assertJsonCount(1, 'data')
->assertJsonPath('data.0.id', $mine->id);
$this->withHeader('Authorization', "Bearer {$token}")
->getJson("/api/v1/bookings/{$mine->booking_ref}")
->assertSuccessful()
->assertJsonPath('data.id', $mine->id);
});
test('a FastAPI JWT gets a 404 for a booking belonging to a different openid', function () {
$someoneElses = Booking::factory()->create(['openid' => 'agent-openid-someone-else']);
$token = fastApiAgentToken('agent-openid-mine');
$this->withHeader('Authorization', "Bearer {$token}")
->getJson("/api/v1/bookings/{$someoneElses->booking_ref}")
->assertNotFound();
});