Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,22 @@ TELEGRAM_BOT_TOKEN=
# SCRIBE_AUTH_KEY=your-api-key-here
# pengaturan cache untuk API, jika ingin menonaktifkan cache, ubah API_CACHE_ENABLED menjadi false
API_CACHE_ENABLED=true
API_CACHE_DURATION=3600 # dalam detik (1 jam)
API_CACHE_DURATION=3600 # dalam detik (1 jam)

# Security Configuration
# Trusted Proxies: Kosongkan untuk tidak trust proxy apapun (default).
# Untuk production di belakang reverse proxy, set ke IP spesifik proxy.
# Contoh Cloudflare IP ranges: https://www.cloudflare.com/ips/
# Contoh multiple proxies: 103.21.244.0/22,103.22.200.0/22
# PERINGATAN: Jangan gunakan '*' di production karena risiko IP spoofing.
# TRUST_PROXIES=

# Rate Limiting Configuration
# Maksimal percobaan login per menit per IP + Email
RATE_LIMIT_LOGIN_MAX=10
# Waktu decay dalam menit sebelum limit di-reset
RATE_LIMIT_LOGIN_DECAY=1

# Rate Limiting untuk OTP (lebih strict dari login)
RATE_LIMIT_OTP_MAX=3
RATE_LIMIT_OTP_DECAY=1
51 changes: 49 additions & 2 deletions app/Http/Middleware/TrustProxies.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,24 +34,71 @@
use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Http\Request;

/**
* Middleware untuk mengatur proxy yang dipercaya.
*
* Konfigurasi ini penting ketika aplikasi berada di belakang reverse proxy
* seperti Nginx, Cloudflare, atau load balancer.
*
* Secure by default: tidak mempercayai proxy apapun kecuali dikonfigurasi eksplisit.
*
* @see https://laravel.com/docs/10.x/requests#configuring-trusted-proxies
*/
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* Secure by default: null berarti tidak trust proxy manapun.
* Untuk production di belakang reverse proxy, set TRUST_PROXIES
* ke IP spesifik proxy (comma-separated) atau gunakan Cloudflare IP ranges.
*
* @var array<int, string>|string|null
*/
protected $proxies;

/**
* The headers that should be used to detect proxies.
*
* Header standar yang dipakai Laravel untuk membaca original client IP
* dari trusted proxy.
*
* @var int
*/
protected $headers =
Request::HEADER_X_FORWARDED_FOR |
protected $headers = Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB;

/**
* Override untuk mendapatkan proxy dari environment variable.
*
* PENTING: TRUST_PROXIES=* TIDAK diizinkan karena risiko IP spoofing.
* Jika TRUST_PROXIES diisi '*', akan diabaikan dan return null.
*
* @return array<int, string>|string|null
*/
protected function proxies()
{
$envProxies = config('security.trusted_proxies');

if ($envProxies === null || $envProxies === '' || $envProxies === '*') {
// Return null: tidak trust proxy headers dari manapun
return null;
}

// Validasi format IP/CIDR sebelum trust
$proxies = array_map('trim', explode(',', $envProxies));
$validProxies = [];

foreach ($proxies as $proxy) {
// Validasi IPv4, IPv6, atau CIDR range
if (filter_var($proxy, FILTER_VALIDATE_IP) || preg_match('/^[\da-fA-F.:]+\/\d+$/', $proxy)) {
$validProxies[] = $proxy;
}
}

return empty($validProxies) ? null : array_values($validProxies);
}
}
2 changes: 1 addition & 1 deletion app/Mail/OtpMail.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public function __construct(int $otp, string $purpose = 'login')
{
$this->otp = $otp;
$this->purpose = $purpose;
$this->expiryMinutes = config('otp.expiry_minutes', 5);
$this->expiryMinutes = max(1, (int) config('otp.expiry_minutes', 5));
}

/**
Expand Down
94 changes: 94 additions & 0 deletions app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,16 @@
use Illuminate\Auth\Events\Failed;
use Illuminate\Auth\Events\Login;
use Illuminate\Auth\Events\Logout;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;
Expand Down Expand Up @@ -88,6 +91,8 @@ public function boot(): void
Paginator::useBootstrap();
$this->paginate();

$this->configureRateLimiting();

if (sudahInstal()) {
$this->penduduk();
$this->config();
Expand Down Expand Up @@ -137,6 +142,95 @@ public function boot(): void
});
}

/**
* Rate limiter untuk login dan OTP (issue #1410).
* (Sebelumnya di RouteServiceProvider::configureRateLimiting()).
*/
protected function configureRateLimiting(): void
{
RateLimiter::for('login', function (Request $request) {
$maxAttempts = max(1, (int) config('security.rate_limit.login.max_attempts'));
$decayMinutes = max(1, (int) config('security.rate_limit.login.decay_minutes'));

$identifier = $this->extractAndValidateIdentifier($request);

return Limit::perMinute($maxAttempts, $decayMinutes)
->by($this->rateLimitKey('login', $request, $identifier));
});

RateLimiter::for('otp', function (Request $request) {
$maxAttempts = max(1, (int) config('security.rate_limit.otp.max_attempts'));
$decayMinutes = max(1, (int) config('security.rate_limit.otp.decay_minutes'));

$identifier = $this->extractAndValidateIdentifier($request);

return Limit::perMinute($maxAttempts, $decayMinutes)
->by($this->rateLimitKey('otp', $request, $identifier));
});
}

/**
* Kunci rate limit: nama limiter + IP klien + identifier.
*
* $request->ip() hanya memakai X-Forwarded-For bila request datang dari
* proxy yang dipercaya (TrustProxies). Jangan membaca header proxy secara
* langsung: klien bisa mengisinya dengan nilai acak di setiap request
* untuk mendapat bucket baru dan melewati batas.
*/
protected function rateLimitKey(string $limiter, Request $request, ?string $identifier): string
{
return $limiter.'|'.$request->ip().'|'.($identifier ?? '');
}

/**
* Extract dan validasi identifier (email/username) dari request.
*
* Validasi:
* - Harus string, bukan array atau tipe lain
* - Batasi panjang maksimal 320 karakter (RFC 5321)
* - Hapus null bytes dan control characters
* - Validasi format email jika terdeteksi sebagai email
*/
protected function extractAndValidateIdentifier(Request $request): ?string
{
$identifier = $request->input('email')
?? $request->input('username')
?? $request->input('identity')
?? $request->input('identifier')
?? data_get($request->session()->get('two-factor:auth'), 'email')
?? data_get($request->session()->get('two-factor:auth'), 'id')
?? data_get($request->session()->get('otp_login'), 'user_id');

// Return null jika tidak ada
if ($identifier === null) {
return null;
}

// Validasi tipe data - harus string
if (! is_string($identifier)) {
return null;
}

// Batasi panjang maksimal (RFC 5321: 320 characters)
if (strlen($identifier) > 320) {
$identifier = substr($identifier, 0, 320);
}

// Hapus null bytes dan control characters
$identifier = preg_replace('/[\x00-\x1F\x7F]/', '', $identifier);

if ($identifier === null) {
return null;
}

$identifier = mb_strtolower(trim($identifier));

// Hanya izinkan karakter yang aman untuk rate limit key
$result = preg_replace('/[^a-z0-9@._-]/', '', $identifier);

return ($result !== null && $result !== '') ? $result : null;
}

/**
* Konfigurasi custom validator untuk data penduduk.
*/
Expand Down
2 changes: 1 addition & 1 deletion app/Services/OtpService.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public function generateAndSave(User $user, string $channel, string $identifier,
->delete();

// Create new token
$expiryMinutes = config('otp.expiry_minutes', 5);
$expiryMinutes = max(1, (int) config('otp.expiry_minutes', 5));
$token = OtpToken::create([
'user_id' => $user->id,
'token_hash' => $tokenHash,
Expand Down
40 changes: 40 additions & 0 deletions config/security.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

return [

/*
|--------------------------------------------------------------------------
| Trusted Proxies
|--------------------------------------------------------------------------
|
| Daftar IP/CIDR reverse proxy yang dipercaya (dipisah koma), misalnya
| Nginx atau Cloudflare. Kosong berarti tidak ada proxy yang dipercaya,
| sehingga header X-Forwarded-For dari klien diabaikan. Nilai '*' ditolak
| di App\Http\Middleware\TrustProxies karena memungkinkan IP spoofing.
|
*/

'trusted_proxies' => env('TRUST_PROXIES'),

/*
|--------------------------------------------------------------------------
| Rate Limiting Login & OTP
|--------------------------------------------------------------------------
|
| Batas percobaan per menit untuk tiap kombinasi IP klien + identitas
| (email/username). Dibaca di AppServiceProvider::configureRateLimiting().
|
*/

'rate_limit' => [
'login' => [
'max_attempts' => (int) env('RATE_LIMIT_LOGIN_MAX', 10),
'decay_minutes' => (int) env('RATE_LIMIT_LOGIN_DECAY', 1),
],
'otp' => [
'max_attempts' => (int) env('RATE_LIMIT_OTP_MAX', 3),
'decay_minutes' => (int) env('RATE_LIMIT_OTP_DECAY', 1),
],
],

];
1 change: 1 addition & 0 deletions phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
<server name="APP_MAINTENANCE_DRIVER" value="file"/>
<server name="BCRYPT_ROUNDS" value="4"/>
<server name="CACHE_STORE" value="array"/>
<server name="CACHE_DRIVER" value="array"/>

<server name="MAIL_MAILER" value="array"/>
<server name="QUEUE_CONNECTION" value="sync"/>
Expand Down
1 change: 1 addition & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@
<server name="APP_MAINTENANCE_DRIVER" value="file"/>
<server name="BCRYPT_ROUNDS" value="4"/>
<server name="CACHE_STORE" value="array"/>
<server name="CACHE_DRIVER" value="array"/>
<server name="DB_CONNECTION" value="sqlite"/>
<server name="DB_DATABASE" value=":memory:"/>
<server name="MAIL_MAILER" value="array"/>
Expand Down
19 changes: 15 additions & 4 deletions routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,11 @@
'register' => false,
]);

Route::namespace('\App\Http\Controllers\Auth')->middleware('guest')->group(function () {
Route::post('/login', 'LoginController@login')
->middleware('throttle:login');
});

// OTP Routes
Route::namespace('\App\Http\Controllers\Auth')->middleware('otp.enabled')->group(function () {
// OTP Activation (requires auth)
Expand All @@ -126,13 +131,18 @@
// OTP Login (guest only)
Route::middleware('guest')->group(function () {
Route::get('/otp/login', 'OtpController@showLoginForm')->name('otp.login');
Route::post('/otp/request-login', 'OtpController@requestLoginOtp')->name('otp.request-login');
Route::post('/otp/request-login', 'OtpController@requestLoginOtp')
->middleware('throttle:otp')
->name('otp.request-login');
Route::get('/otp/verify-login', 'OtpController@showVerifyLoginForm')->name('otp.verify-login');
Route::post('/otp/verify-login', 'OtpController@loginWithOtp');
Route::post('/otp/verify-login', 'OtpController@loginWithOtp')
->middleware('throttle:login');
});

// OTP Resend (both auth and guest)
Route::post('/otp/resend', 'OtpController@resendOtp')->name('otp.resend');
Route::post('/otp/resend', 'OtpController@resendOtp')
->middleware('throttle:otp')
->name('otp.resend');
});

// 2FA Routes
Expand Down Expand Up @@ -166,7 +176,8 @@
// 2FA Login Routes (guest access)
Route::namespace('\App\Http\Controllers\Auth')->middleware('guest')->group(function () {
Route::get('/2fa/verify-login', 'TwoFactorController@showVerifyLoginForm')->name('2fa.verify-login');
Route::post('/2fa/verify-login', 'TwoFactorController@verifyLogin');
Route::post('/2fa/verify-login', 'TwoFactorController@verifyLogin')
->middleware('throttle:login');
});

Route::group(['prefix' => 'filemanager', 'middleware' => ['auth:web', 'action_permission:access.setting']], function () {
Expand Down
6 changes: 6 additions & 0 deletions tests/Feature/LembagaControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,9 @@ function getLembagaKategori()
['value' => '1']
);

// Jangan bergantung pada cache 'listDesa' dari tes sebelumnya.
Http::fake(['*' => Http::response(['data' => []], 200)]);

$penduduk = getLembagaPenduduk();
$kategori = getLembagaKategori();

Expand All @@ -213,6 +216,9 @@ function getLembagaKategori()
['value' => '1']
);

// Jangan bergantung pada cache 'listDesa' dari tes sebelumnya.
Http::fake(['*' => Http::response(['data' => []], 200)]);

$penduduk = getLembagaPenduduk();
$kategori = getLembagaKategori();
$lembaga = Lembaga::factory()->create([
Expand Down
Loading