Phase 6: security & ops hardening (T6.1-T6.5)
- T6.1: named rate limiters (api-read/api-write/api-auth/api-webhooks), applied per module route group with tighter limits on booking/payment writes and the KBZ webhook than read-only catalog/routing endpoints. - T6.2: install spatie/laravel-activitylog; LogsActivity on Booking/ Payment/Refund status transitions and catalog/pricing admin CRUD (EvCompany, Destination, DepartureTimeSlot, EvRoute, RoutePricing). New IdentityPlugin with a read-only AuditLogResource gated by view_audit_log. - T6.3: JSON error envelope for api/* in bootstrap/app.php (401/403/404/ 405/429/500 fallback), plus PaymentGatewayException (422 declined / 502 unavailable). - T6.4: feature tests proving the FastAPI agent token gets 403 on refund/cancel-not-owned and 405 (no write handler) on catalog/routing writes. - T6.5: install gboquizosanchez/filament-log-viewer with a custom Filament admin theme (required for its views' Tailwind classes to compile), LOG_CHANNEL/FILAMENT_LOG_VIEWER_DRIVER=daily, registered under Operations in the sidebar. 252 tests passing.
This commit is contained in:
@@ -3,7 +3,7 @@
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Modules\Booking\Http\Controllers\BookingController;
|
||||
|
||||
Route::prefix('api/v1')->middleware(['api', 'auth:sanctum', 'throttle:60,1'])->group(function () {
|
||||
Route::prefix('api/v1')->middleware(['api', 'auth:sanctum', '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');
|
||||
|
||||
@@ -13,11 +13,26 @@ use Modules\Booking\Enums\BookingStatus;
|
||||
use Modules\Catalog\Models\DepartureTimeSlot;
|
||||
use Modules\Payment\Models\Payment;
|
||||
use Modules\Routing\Models\EvRoute;
|
||||
use Spatie\Activitylog\Models\Concerns\LogsActivity;
|
||||
use Spatie\Activitylog\Support\LogOptions;
|
||||
|
||||
class Booking extends Model
|
||||
{
|
||||
/** @use HasFactory<BookingFactory> */
|
||||
use HasFactory;
|
||||
use HasFactory, LogsActivity;
|
||||
|
||||
/**
|
||||
* Audit trail on status transitions and driver/vehicle assignment only —
|
||||
* not every column (domain.md §6, §5a; T6.2).
|
||||
*/
|
||||
public function getActivitylogOptions(): LogOptions
|
||||
{
|
||||
return LogOptions::defaults()
|
||||
->logOnly(['status', 'driver_name', 'driver_phone', 'car_plate_number', 'car_model'])
|
||||
->logOnlyDirty()
|
||||
->dontLogEmptyChanges()
|
||||
->useLogName('booking');
|
||||
}
|
||||
|
||||
/**
|
||||
* @var list<string>
|
||||
|
||||
@@ -4,7 +4,7 @@ use Illuminate\Support\Facades\Route;
|
||||
use Modules\Catalog\Http\Controllers\DestinationController;
|
||||
use Modules\Catalog\Http\Controllers\EvCompanyController;
|
||||
|
||||
Route::prefix('api/v1')->middleware(['api', 'auth:sanctum', 'throttle:60,1'])->group(function () {
|
||||
Route::prefix('api/v1')->middleware(['api', 'auth:sanctum', 'throttle:api-read'])->group(function () {
|
||||
Route::get('/companies', [EvCompanyController::class, 'index'])->name('catalog.companies.index');
|
||||
Route::get('/destinations', [DestinationController::class, 'index'])->name('catalog.destinations.index');
|
||||
});
|
||||
|
||||
@@ -7,6 +7,8 @@ use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Modules\Catalog\Database\Factories\DepartureTimeSlotFactory;
|
||||
use Modules\Routing\Models\EvRoute;
|
||||
use Spatie\Activitylog\Models\Concerns\LogsActivity;
|
||||
use Spatie\Activitylog\Support\LogOptions;
|
||||
|
||||
/**
|
||||
* A shared catalog of departure times, attached to routes via a pivot in the
|
||||
@@ -15,7 +17,21 @@ use Modules\Routing\Models\EvRoute;
|
||||
class DepartureTimeSlot extends Model
|
||||
{
|
||||
/** @use HasFactory<DepartureTimeSlotFactory> */
|
||||
use HasFactory;
|
||||
use HasFactory, LogsActivity;
|
||||
|
||||
/**
|
||||
* Full CRUD audit trail — catalog admin writes are staff-only and
|
||||
* infrequent, so logging every attribute change is affordable
|
||||
* (domain.md §6; T6.2).
|
||||
*/
|
||||
public function getActivitylogOptions(): LogOptions
|
||||
{
|
||||
return LogOptions::defaults()
|
||||
->logFillable()
|
||||
->logOnlyDirty()
|
||||
->dontLogEmptyChanges()
|
||||
->useLogName('catalog');
|
||||
}
|
||||
|
||||
/**
|
||||
* @var list<string>
|
||||
|
||||
@@ -5,11 +5,27 @@ namespace Modules\Catalog\Models;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Modules\Catalog\Database\Factories\DestinationFactory;
|
||||
use Spatie\Activitylog\Models\Concerns\LogsActivity;
|
||||
use Spatie\Activitylog\Support\LogOptions;
|
||||
|
||||
class Destination extends Model
|
||||
{
|
||||
/** @use HasFactory<DestinationFactory> */
|
||||
use HasFactory;
|
||||
use HasFactory, LogsActivity;
|
||||
|
||||
/**
|
||||
* Full CRUD audit trail — catalog admin writes are staff-only and
|
||||
* infrequent, so logging every attribute change is affordable
|
||||
* (domain.md §6; T6.2).
|
||||
*/
|
||||
public function getActivitylogOptions(): LogOptions
|
||||
{
|
||||
return LogOptions::defaults()
|
||||
->logFillable()
|
||||
->logOnlyDirty()
|
||||
->dontLogEmptyChanges()
|
||||
->useLogName('catalog');
|
||||
}
|
||||
|
||||
/**
|
||||
* @var list<string>
|
||||
|
||||
@@ -6,11 +6,27 @@ use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Str;
|
||||
use Modules\Catalog\Database\Factories\EvCompanyFactory;
|
||||
use Spatie\Activitylog\Models\Concerns\LogsActivity;
|
||||
use Spatie\Activitylog\Support\LogOptions;
|
||||
|
||||
class EvCompany extends Model
|
||||
{
|
||||
/** @use HasFactory<EvCompanyFactory> */
|
||||
use HasFactory;
|
||||
use HasFactory, LogsActivity;
|
||||
|
||||
/**
|
||||
* Full CRUD audit trail — catalog admin writes are staff-only and
|
||||
* infrequent, so logging every attribute change is affordable
|
||||
* (domain.md §6; T6.2).
|
||||
*/
|
||||
public function getActivitylogOptions(): LogOptions
|
||||
{
|
||||
return LogOptions::defaults()
|
||||
->logFillable()
|
||||
->logOnlyDirty()
|
||||
->dontLogEmptyChanges()
|
||||
->useLogName('catalog');
|
||||
}
|
||||
|
||||
/**
|
||||
* @var list<string>
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Modules\Identity\Http\Controllers\TokenController;
|
||||
|
||||
Route::prefix('api/v1')->middleware('api')->group(function () {
|
||||
Route::prefix('api/v1')->middleware(['api', 'throttle:api-auth'])->group(function () {
|
||||
Route::post('/auth/token', [TokenController::class, 'store'])->name('identity.auth.token');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Identity\Filament\Resources\AuditLogs;
|
||||
|
||||
use BackedEnum;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Table;
|
||||
use Modules\Identity\Filament\Resources\AuditLogs\Pages\ListAuditLogs;
|
||||
use Modules\Identity\Filament\Resources\AuditLogs\Pages\ViewAuditLog;
|
||||
use Modules\Identity\Filament\Resources\AuditLogs\Schemas\AuditLogInfolist;
|
||||
use Modules\Identity\Filament\Resources\AuditLogs\Tables\AuditLogsTable;
|
||||
use Spatie\Activitylog\Models\Activity;
|
||||
use UnitEnum;
|
||||
|
||||
/**
|
||||
* Read-only by design (T6.2, gated by view_audit_log — AuditLogPolicy):
|
||||
* every row here comes from the LogsActivity trait on Booking/Payment/
|
||||
* Refund/catalog/pricing models, never hand-entered.
|
||||
*/
|
||||
class AuditLogResource extends Resource
|
||||
{
|
||||
protected static ?string $model = Activity::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedClipboardDocumentList;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Access';
|
||||
|
||||
protected static ?string $navigationLabel = 'Audit Log';
|
||||
|
||||
protected static ?string $modelLabel = 'Audit Log Entry';
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return AuditLogsTable::configure($table);
|
||||
}
|
||||
|
||||
public static function infolist(Schema $schema): Schema
|
||||
{
|
||||
return AuditLogInfolist::configure($schema);
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListAuditLogs::route('/'),
|
||||
'view' => ViewAuditLog::route('/{record}'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Identity\Filament\Resources\AuditLogs\Pages;
|
||||
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Modules\Identity\Filament\Resources\AuditLogs\AuditLogResource;
|
||||
|
||||
class ListAuditLogs extends ListRecords
|
||||
{
|
||||
protected static string $resource = AuditLogResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
// No CreateAction — audit log rows are only ever written by the
|
||||
// LogsActivity trait, never hand-entered here.
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Identity\Filament\Resources\AuditLogs\Pages;
|
||||
|
||||
use Filament\Resources\Pages\ViewRecord;
|
||||
use Modules\Identity\Filament\Resources\AuditLogs\AuditLogResource;
|
||||
|
||||
class ViewAuditLog extends ViewRecord
|
||||
{
|
||||
protected static string $resource = AuditLogResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
// Read-only — no EditAction/DeleteAction.
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Identity\Filament\Resources\AuditLogs\Schemas;
|
||||
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Schemas\Components\Grid;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Schema;
|
||||
|
||||
class AuditLogInfolist
|
||||
{
|
||||
public static function configure(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->components([
|
||||
Section::make('Event')
|
||||
->schema([
|
||||
Grid::make(3)
|
||||
->schema([
|
||||
TextEntry::make('log_name')->label('Module')->badge(),
|
||||
TextEntry::make('event')->badge()->placeholder('—'),
|
||||
TextEntry::make('created_at')->dateTime(),
|
||||
TextEntry::make('subject_type')->label('Subject Type')->placeholder('—'),
|
||||
TextEntry::make('subject_id')->label('Subject ID')->placeholder('—'),
|
||||
TextEntry::make('causer.name')->label('Caused By')->placeholder('System'),
|
||||
]),
|
||||
TextEntry::make('description')->columnSpanFull(),
|
||||
]),
|
||||
Section::make('Changes')
|
||||
->schema([
|
||||
TextEntry::make('attribute_changes')
|
||||
->label('')
|
||||
->formatStateUsing(fn (mixed $state) => $state
|
||||
? json_encode($state, JSON_PRETTY_PRINT)
|
||||
: null)
|
||||
->placeholder('—')
|
||||
->columnSpanFull(),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Identity\Filament\Resources\AuditLogs\Tables;
|
||||
|
||||
use Filament\Actions\ViewAction;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\SelectFilter;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Str;
|
||||
use Spatie\Activitylog\Models\Activity;
|
||||
|
||||
class AuditLogsTable
|
||||
{
|
||||
public static function configure(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->modifyQueryUsing(fn (Builder $query) => $query->with(['causer', 'subject']))
|
||||
->defaultSort('created_at', 'desc')
|
||||
->columns([
|
||||
TextColumn::make('created_at')
|
||||
->dateTime()
|
||||
->sortable(),
|
||||
TextColumn::make('log_name')
|
||||
->label('Module')
|
||||
->badge(),
|
||||
TextColumn::make('event')
|
||||
->badge()
|
||||
->color(fn (?string $state) => match ($state) {
|
||||
'created' => 'success',
|
||||
'updated' => 'warning',
|
||||
'deleted' => 'danger',
|
||||
default => 'gray',
|
||||
})
|
||||
->placeholder('—'),
|
||||
TextColumn::make('subject_type')
|
||||
->label('Subject')
|
||||
->formatStateUsing(fn (?string $state) => $state ? Str::afterLast($state, '\\') : '—')
|
||||
->description(fn (Activity $record) => $record->subject_id ? "#{$record->subject_id}" : null),
|
||||
TextColumn::make('description')
|
||||
->wrap(),
|
||||
TextColumn::make('causer.name')
|
||||
->label('Caused By')
|
||||
->placeholder('System')
|
||||
->searchable(),
|
||||
])
|
||||
->filters([
|
||||
SelectFilter::make('log_name')
|
||||
->label('Module')
|
||||
->options(fn () => Activity::query()->distinct()->pluck('log_name', 'log_name')->filter()->all()),
|
||||
SelectFilter::make('event')
|
||||
->options([
|
||||
'created' => 'Created',
|
||||
'updated' => 'Updated',
|
||||
'deleted' => 'Deleted',
|
||||
]),
|
||||
])
|
||||
->recordActions([
|
||||
ViewAction::make(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Identity;
|
||||
|
||||
use Filament\Contracts\Plugin;
|
||||
use Filament\Panel;
|
||||
|
||||
/**
|
||||
* Thin Access-management plugin (see tickets.md T1.3) — Identity has no
|
||||
* customer-facing CRUD of its own, just the read-only AuditLogResource
|
||||
* (T6.2) discovered here.
|
||||
*/
|
||||
class IdentityPlugin implements Plugin
|
||||
{
|
||||
public function getId(): string
|
||||
{
|
||||
return 'identity';
|
||||
}
|
||||
|
||||
public function register(Panel $panel): void
|
||||
{
|
||||
$panel
|
||||
->discoverResources(
|
||||
in: __DIR__.'/Filament/Resources',
|
||||
for: 'Modules\Identity\Filament\Resources',
|
||||
)
|
||||
->discoverPages(
|
||||
in: __DIR__.'/Filament/Pages',
|
||||
for: 'Modules\Identity\Filament\Pages',
|
||||
)
|
||||
->discoverWidgets(
|
||||
in: __DIR__.'/Filament/Widgets',
|
||||
for: 'Modules\Identity\Filament\Widgets',
|
||||
);
|
||||
}
|
||||
|
||||
public function boot(Panel $panel): void {}
|
||||
|
||||
public static function make(): static
|
||||
{
|
||||
return app(static::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Identity\Policies;
|
||||
|
||||
use App\Models\User;
|
||||
use Spatie\Activitylog\Models\Activity;
|
||||
|
||||
/**
|
||||
* The audit trail (T6.2) is read-only from the admin panel — nothing ever
|
||||
* creates/edits/deletes an Activity row through Filament, only the
|
||||
* LogsActivity trait writes here. Gated by view_audit_log per domain.md §8.
|
||||
*/
|
||||
class AuditLogPolicy
|
||||
{
|
||||
public function viewAny(User $user): bool
|
||||
{
|
||||
return $user->can('view_audit_log');
|
||||
}
|
||||
|
||||
public function view(User $user, Activity $activity): bool
|
||||
{
|
||||
return $user->can('view_audit_log');
|
||||
}
|
||||
|
||||
public function create(User $user): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function update(User $user, Activity $activity): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function delete(User $user, Activity $activity): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,17 @@
|
||||
|
||||
namespace Modules\Identity\Providers;
|
||||
|
||||
use Illuminate\Contracts\Auth\Access\Gate;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Modules\Identity\Policies\AuditLogPolicy;
|
||||
use Spatie\Activitylog\Models\Activity;
|
||||
|
||||
class IdentityServiceProvider extends ServiceProvider
|
||||
{
|
||||
public function register(): void {}
|
||||
|
||||
public function boot(): void {}
|
||||
public function boot(Gate $gate): void
|
||||
{
|
||||
$gate->policy(Activity::class, AuditLogPolicy::class);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use Modules\Booking\Enums\BookingStatus;
|
||||
use Modules\Booking\Models\Booking;
|
||||
use Modules\Identity\Enums\TokenAbility;
|
||||
use Modules\Payment\Enums\PaymentMethod;
|
||||
use Modules\Payment\Models\Payment;
|
||||
|
||||
/**
|
||||
* T6.4 — full policy + agent-ability audit (domain.md §8). The FastAPI
|
||||
* agent's token is scoped to route:read/booking:create/booking:read only;
|
||||
* this proves that scope is actually enforced end-to-end (via the existing
|
||||
* role/permission-based policies, not a token-ability route middleware) and
|
||||
* that catalog/pricing writes have no customer-facing route at all.
|
||||
*/
|
||||
beforeEach(function () {
|
||||
$this->agent = User::factory()->create();
|
||||
$this->agentToken = $this->agent->createToken('fastapi-agent', TokenAbility::fastApiAgentAbilities())->plainTextToken;
|
||||
});
|
||||
|
||||
test('the agent token cannot refund a confirmed booking', function () {
|
||||
$booking = Booking::factory()->create(['status' => BookingStatus::Confirmed, 'price' => 15000]);
|
||||
Payment::factory()->completed()->create([
|
||||
'booking_id' => $booking->id,
|
||||
'gateway' => PaymentMethod::KbzMiniApp,
|
||||
'amount' => 15000,
|
||||
'gateway_transaction_id' => 'EVB-AGENT-AUDIT-1',
|
||||
]);
|
||||
|
||||
$this->withHeader('Authorization', "Bearer {$this->agentToken}")
|
||||
->postJson("/api/v1/bookings/{$booking->booking_ref}/refund", [
|
||||
'amount' => 15000,
|
||||
'reason' => 'agent should never reach this',
|
||||
])
|
||||
->assertForbidden();
|
||||
|
||||
expect($booking->refresh()->status)->toBe(BookingStatus::Confirmed);
|
||||
});
|
||||
|
||||
test('the agent token cannot cancel a booking it does not own', function () {
|
||||
$owner = User::factory()->create();
|
||||
$booking = Booking::factory()->create(['user_id' => $owner->id, 'status' => BookingStatus::PendingPayment]);
|
||||
|
||||
$this->withHeader('Authorization', "Bearer {$this->agentToken}")
|
||||
->postJson("/api/v1/bookings/{$booking->booking_ref}/cancel")
|
||||
->assertForbidden();
|
||||
|
||||
expect($booking->refresh()->status)->toBe(BookingStatus::PendingPayment);
|
||||
});
|
||||
|
||||
test('catalog writes have no customer-facing route at all', function () {
|
||||
// These paths only exist as GET (read) routes — a POST to them is
|
||||
// rejected as 405 (method not allowed), not routed to any write
|
||||
// handler, proving no write endpoint was ever registered.
|
||||
$this->withHeader('Authorization', "Bearer {$this->agentToken}")
|
||||
->postJson('/api/v1/companies', ['name' => 'Should Not Exist'])
|
||||
->assertStatus(405);
|
||||
|
||||
$this->withHeader('Authorization', "Bearer {$this->agentToken}")
|
||||
->postJson('/api/v1/destinations', ['name' => 'Should Not Exist'])
|
||||
->assertStatus(405);
|
||||
});
|
||||
|
||||
test('routing/pricing writes have no customer-facing route at all', function () {
|
||||
$this->withHeader('Authorization', "Bearer {$this->agentToken}")
|
||||
->postJson('/api/v1/routes', ['ev_company_id' => 1])
|
||||
->assertStatus(405);
|
||||
});
|
||||
|
||||
test('the agent token can still read routes and create/read bookings', function () {
|
||||
$this->withHeader('Authorization', "Bearer {$this->agentToken}")
|
||||
->getJson('/api/v1/routes')
|
||||
->assertSuccessful();
|
||||
|
||||
$booking = Booking::factory()->create(['user_id' => $this->agent->id]);
|
||||
|
||||
$this->withHeader('Authorization', "Bearer {$this->agentToken}")
|
||||
->getJson('/api/v1/bookings')
|
||||
->assertSuccessful()
|
||||
->assertJsonPath('data.0.id', $booking->id);
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use Modules\Booking\Enums\BookingStatus;
|
||||
use Modules\Booking\Models\Booking;
|
||||
use Modules\Catalog\Models\EvCompany;
|
||||
use Spatie\Activitylog\Models\Activity;
|
||||
use Spatie\Permission\Models\Permission;
|
||||
use Spatie\Permission\Models\Role;
|
||||
|
||||
/**
|
||||
* T6.2 — LogsActivity is attached to Booking status transitions and to
|
||||
* catalog admin CRUD; the read-only AuditLogResource (Filament) is gated by
|
||||
* view_audit_log.
|
||||
*/
|
||||
test('a booking status transition is recorded in the audit log', function () {
|
||||
$booking = Booking::factory()->create(['status' => BookingStatus::PendingPayment]);
|
||||
|
||||
$booking->update(['status' => BookingStatus::Confirmed]);
|
||||
|
||||
$activity = Activity::where('subject_type', Booking::class)
|
||||
->where('subject_id', $booking->id)
|
||||
->where('log_name', 'booking')
|
||||
->latest('id')
|
||||
->first();
|
||||
|
||||
expect($activity)->not->toBeNull();
|
||||
expect($activity->attribute_changes->get('attributes'))->toMatchArray(['status' => BookingStatus::Confirmed->value]);
|
||||
});
|
||||
|
||||
test('a catalog CRUD write is recorded in the audit log', function () {
|
||||
$company = EvCompany::factory()->create(['name' => 'Original Name']);
|
||||
|
||||
$company->update(['name' => 'Renamed Company']);
|
||||
|
||||
$activity = Activity::where('subject_type', EvCompany::class)
|
||||
->where('subject_id', $company->id)
|
||||
->where('log_name', 'catalog')
|
||||
->latest('id')
|
||||
->first();
|
||||
|
||||
expect($activity)->not->toBeNull();
|
||||
expect($activity->attribute_changes->get('attributes')['name'])->toBe('Renamed Company');
|
||||
});
|
||||
|
||||
test('a user without view_audit_log cannot list the audit log via Filament', function () {
|
||||
Permission::findOrCreate('view_audit_log', 'web');
|
||||
$role = Role::findOrCreate('support', 'web');
|
||||
$user = User::factory()->create();
|
||||
$user->assignRole($role);
|
||||
|
||||
$this->actingAs($user)
|
||||
->get('/admin/audit-logs')
|
||||
->assertForbidden();
|
||||
});
|
||||
|
||||
test('a user with view_audit_log can list the audit log via Filament', function () {
|
||||
Permission::findOrCreate('view_audit_log', 'web');
|
||||
$role = Role::findOrCreate('support', 'web');
|
||||
$role->givePermissionTo('view_audit_log');
|
||||
$user = User::factory()->create();
|
||||
$user->assignRole($role);
|
||||
|
||||
$this->actingAs($user)
|
||||
->get('/admin/audit-logs')
|
||||
->assertSuccessful();
|
||||
});
|
||||
@@ -5,7 +5,7 @@ use Modules\Payment\Http\Controllers\PaymentController;
|
||||
use Modules\Payment\Http\Controllers\PaymentWebhookController;
|
||||
use Modules\Payment\Http\Controllers\RefundController;
|
||||
|
||||
Route::prefix('api/v1')->middleware(['api', 'auth:sanctum', 'throttle:60,1'])->group(function () {
|
||||
Route::prefix('api/v1')->middleware(['api', 'auth:sanctum', 'throttle:api-write'])->group(function () {
|
||||
Route::post('/payments/{booking:booking_ref}/initiate', [PaymentController::class, 'initiate'])->name('payment.payments.initiate');
|
||||
Route::post('/bookings/{booking:booking_ref}/refund', [RefundController::class, 'refund'])->name('payment.bookings.refund');
|
||||
});
|
||||
@@ -13,6 +13,6 @@ Route::prefix('api/v1')->middleware(['api', 'auth:sanctum', 'throttle:60,1'])->g
|
||||
// No auth:sanctum — the gateway authenticates itself via its own signed
|
||||
// payload (verified inside each gateway's handleWebhook()), not a bearer
|
||||
// token (domain.md §6).
|
||||
Route::prefix('api/v1')->middleware(['api', 'throttle:60,1'])->group(function () {
|
||||
Route::prefix('api/v1')->middleware(['api', 'throttle:api-webhooks'])->group(function () {
|
||||
Route::post('/webhooks/{method}/{encryptBookingId?}', [PaymentWebhookController::class, 'handle'])->name('payment.webhooks.handle');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Payment\Exceptions;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* Carries a gateway's own error code/message for an unexpected failure that
|
||||
* isn't already captured as a typed Failed result (e.g. a malformed
|
||||
* response the gateway strategy can't parse into a PaymentResultData/
|
||||
* RefundResultData). Never allowed to surface as a raw 500 (domain.md §6,
|
||||
* T6.3): a declined/rejected call from the gateway itself is a 422 (client
|
||||
* can retry/fix), an unreachable/misbehaving gateway is a 502.
|
||||
*/
|
||||
class PaymentGatewayException extends RuntimeException
|
||||
{
|
||||
private function __construct(
|
||||
string $message,
|
||||
private readonly int $statusCode,
|
||||
private readonly ?string $gatewayCode = null,
|
||||
) {
|
||||
parent::__construct($message);
|
||||
}
|
||||
|
||||
/**
|
||||
* The gateway responded but rejected/declined the request — surfaced as
|
||||
* 422 since it's a business outcome the caller can act on.
|
||||
*/
|
||||
public static function declined(string $message, ?string $gatewayCode = null): self
|
||||
{
|
||||
return new self($message, 422, $gatewayCode);
|
||||
}
|
||||
|
||||
/**
|
||||
* The gateway didn't respond usefully at all (unreachable, malformed
|
||||
* payload, unexpected HTTP status) — surfaced as 502, our fault for
|
||||
* depending on it, not the caller's.
|
||||
*/
|
||||
public static function unavailable(string $message, ?string $gatewayCode = null): self
|
||||
{
|
||||
return new self($message, 502, $gatewayCode);
|
||||
}
|
||||
|
||||
public function render(Request $request): ?JsonResponse
|
||||
{
|
||||
if ($request->expectsJson()) {
|
||||
return response()->json([
|
||||
'message' => $this->getMessage(),
|
||||
'gateway_code' => $this->gatewayCode,
|
||||
], $this->statusCode);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ use Modules\Booking\Models\Booking;
|
||||
use Modules\Payment\Database\Factories\PaymentFactory;
|
||||
use Modules\Payment\Enums\PaymentMethod;
|
||||
use Modules\Payment\Enums\PaymentStatus;
|
||||
use Spatie\Activitylog\Models\Concerns\LogsActivity;
|
||||
use Spatie\Activitylog\Support\LogOptions;
|
||||
|
||||
/**
|
||||
* One attempt to pay for a Booking through a gateway — a Booking can have
|
||||
@@ -19,7 +21,19 @@ use Modules\Payment\Enums\PaymentStatus;
|
||||
class Payment extends Model
|
||||
{
|
||||
/** @use HasFactory<PaymentFactory> */
|
||||
use HasFactory;
|
||||
use HasFactory, LogsActivity;
|
||||
|
||||
/**
|
||||
* Audit trail on status transitions only (domain.md §6; T6.2).
|
||||
*/
|
||||
public function getActivitylogOptions(): LogOptions
|
||||
{
|
||||
return LogOptions::defaults()
|
||||
->logOnly(['status'])
|
||||
->logOnlyDirty()
|
||||
->dontLogEmptyChanges()
|
||||
->useLogName('payment');
|
||||
}
|
||||
|
||||
/**
|
||||
* @var list<string>
|
||||
|
||||
@@ -8,6 +8,8 @@ use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Modules\Payment\Database\Factories\RefundFactory;
|
||||
use Modules\Payment\Enums\RefundStatus;
|
||||
use Spatie\Activitylog\Models\Concerns\LogsActivity;
|
||||
use Spatie\Activitylog\Support\LogOptions;
|
||||
|
||||
/**
|
||||
* A reversal against a specific successful Payment (not against the Booking
|
||||
@@ -17,7 +19,19 @@ use Modules\Payment\Enums\RefundStatus;
|
||||
class Refund extends Model
|
||||
{
|
||||
/** @use HasFactory<RefundFactory> */
|
||||
use HasFactory;
|
||||
use HasFactory, LogsActivity;
|
||||
|
||||
/**
|
||||
* Audit trail on status transitions only (domain.md §6; T6.2).
|
||||
*/
|
||||
public function getActivitylogOptions(): LogOptions
|
||||
{
|
||||
return LogOptions::defaults()
|
||||
->logOnly(['status'])
|
||||
->logOnlyDirty()
|
||||
->dontLogEmptyChanges()
|
||||
->useLogName('refund');
|
||||
}
|
||||
|
||||
/**
|
||||
* @var list<string>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Modules\Routing\Http\Controllers\EvRouteController;
|
||||
|
||||
Route::prefix('api/v1')->middleware(['api', 'auth:sanctum', 'throttle:60,1'])->group(function () {
|
||||
Route::prefix('api/v1')->middleware(['api', 'auth:sanctum', 'throttle:api-read'])->group(function () {
|
||||
Route::get('/routes', [EvRouteController::class, 'index'])->name('routing.routes.index');
|
||||
Route::get('/routes/{route}', [EvRouteController::class, 'show'])->name('routing.routes.show');
|
||||
Route::get('/routes/{route}/pricing', [EvRouteController::class, 'pricing'])->name('routing.routes.pricing');
|
||||
|
||||
@@ -12,11 +12,27 @@ use Modules\Catalog\Models\DepartureTimeSlot;
|
||||
use Modules\Catalog\Models\Destination;
|
||||
use Modules\Catalog\Models\EvCompany;
|
||||
use Modules\Routing\Database\Factories\EvRouteFactory;
|
||||
use Spatie\Activitylog\Models\Concerns\LogsActivity;
|
||||
use Spatie\Activitylog\Support\LogOptions;
|
||||
|
||||
class EvRoute extends Model
|
||||
{
|
||||
/** @use HasFactory<EvRouteFactory> */
|
||||
use HasFactory;
|
||||
use HasFactory, LogsActivity;
|
||||
|
||||
/**
|
||||
* Full CRUD audit trail — route admin writes are staff-only and
|
||||
* infrequent, so logging every attribute change is affordable
|
||||
* (domain.md §6; T6.2).
|
||||
*/
|
||||
public function getActivitylogOptions(): LogOptions
|
||||
{
|
||||
return LogOptions::defaults()
|
||||
->logFillable()
|
||||
->logOnlyDirty()
|
||||
->dontLogEmptyChanges()
|
||||
->useLogName('routing');
|
||||
}
|
||||
|
||||
/**
|
||||
* @var list<string>
|
||||
|
||||
@@ -7,11 +7,27 @@ use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Modules\Routing\Database\Factories\RoutePricingFactory;
|
||||
use Modules\Shared\Enums\VehicleOption;
|
||||
use Spatie\Activitylog\Models\Concerns\LogsActivity;
|
||||
use Spatie\Activitylog\Support\LogOptions;
|
||||
|
||||
class RoutePricing extends Model
|
||||
{
|
||||
/** @use HasFactory<RoutePricingFactory> */
|
||||
use HasFactory;
|
||||
use HasFactory, LogsActivity;
|
||||
|
||||
/**
|
||||
* Full CRUD audit trail — pricing changes must never silently reprice
|
||||
* existing bookings (domain.md §3), so every edit here is traceable to
|
||||
* who changed it and when (T6.2).
|
||||
*/
|
||||
public function getActivitylogOptions(): LogOptions
|
||||
{
|
||||
return LogOptions::defaults()
|
||||
->logFillable()
|
||||
->logOnlyDirty()
|
||||
->dontLogEmptyChanges()
|
||||
->useLogName('routing');
|
||||
}
|
||||
|
||||
protected $table = 'route_pricing';
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
|
||||
/**
|
||||
* T6.3 — every exception reaching an api/* route gets a consistent JSON
|
||||
* envelope, regardless of the client's Accept header, and never a bare
|
||||
* unenveloped 500 (bootstrap/app.php).
|
||||
*/
|
||||
test('an unauthenticated request to a protected api route gets a 401 JSON envelope', function () {
|
||||
$this->postJson('/api/v1/bookings/EVB-DOES-NOT-EXIST/cancel')
|
||||
->assertUnauthorized()
|
||||
->assertJsonStructure(['message']);
|
||||
});
|
||||
|
||||
test('a route model binding miss on an api route gets a 404 JSON envelope', function () {
|
||||
$user = User::factory()->create();
|
||||
$token = $user->createToken('test')->plainTextToken;
|
||||
|
||||
$this->withHeader('Authorization', "Bearer {$token}")
|
||||
->getJson('/api/v1/bookings/EVB-DOES-NOT-EXIST')
|
||||
->assertNotFound()
|
||||
->assertJsonStructure(['message']);
|
||||
});
|
||||
|
||||
test('an unknown api route gets a 404 JSON envelope, not an HTML page', function () {
|
||||
$this->getJson('/api/v1/this-route-does-not-exist')
|
||||
->assertNotFound()
|
||||
->assertJsonStructure(['message']);
|
||||
});
|
||||
|
||||
test('an unsupported HTTP method on a known api route gets a 405 JSON envelope', function () {
|
||||
$this->putJson('/api/v1/companies')
|
||||
->assertStatus(405)
|
||||
->assertJsonStructure(['message']);
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
|
||||
/**
|
||||
* T6.1 — write-heavy booking/payment endpoints are throttled tighter than
|
||||
* read-only catalog/routing endpoints (domain.md §8).
|
||||
*/
|
||||
test('the booking write limiter is tighter than the catalog read limiter', function () {
|
||||
$user = User::factory()->create();
|
||||
$token = $user->createToken('test')->plainTextToken;
|
||||
|
||||
$readResponses = collect(range(1, 25))->map(
|
||||
fn () => $this->withHeader('Authorization', "Bearer {$token}")->getJson('/api/v1/companies')
|
||||
);
|
||||
expect($readResponses->every(fn ($response) => $response->status() !== 429))->toBeTrue();
|
||||
|
||||
$writeResponses = collect(range(1, 25))->map(
|
||||
fn () => $this->withHeader('Authorization', "Bearer {$token}")->postJson('/api/v1/bookings', [])
|
||||
);
|
||||
expect($writeResponses->contains(fn ($response) => $response->status() === 429))->toBeTrue();
|
||||
});
|
||||
|
||||
test('a rate-limited api request gets a 429 JSON envelope', function () {
|
||||
$user = User::factory()->create();
|
||||
$token = $user->createToken('test')->plainTextToken;
|
||||
|
||||
$responses = collect(range(1, 25))->map(
|
||||
fn () => $this->withHeader('Authorization', "Bearer {$token}")->postJson('/api/v1/bookings', [])
|
||||
);
|
||||
|
||||
$limited = $responses->first(fn ($response) => $response->status() === 429);
|
||||
|
||||
expect($limited)->not->toBeNull();
|
||||
$limited->assertJsonStructure(['message']);
|
||||
});
|
||||
Reference in New Issue
Block a user