first init
This commit is contained in:
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class ApiKeyAuthenticationMiddleware
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
// Check if API key authentication is enabled
|
||||
if (!config('api_security.enable_api_key_auth', true)) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
// Get API key from request
|
||||
$apiKey = $this->extractApiKey($request);
|
||||
|
||||
if (!$apiKey) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'API key is required for external system access.',
|
||||
'error' => 'API_KEY_REQUIRED'
|
||||
], 401);
|
||||
}
|
||||
|
||||
// Validate API key
|
||||
if (!$this->isValidApiKey($apiKey)) {
|
||||
// Log invalid API key attempt
|
||||
if (config('api_security.log_api_key_usage', true)) {
|
||||
Log::warning('Invalid API key attempt', [
|
||||
'ip' => $request->ip(),
|
||||
'user_agent' => $request->header('User-Agent'),
|
||||
'endpoint' => $request->fullUrl(),
|
||||
'method' => $request->method(),
|
||||
'api_key_prefix' => substr($apiKey, 0, 8) . '...',
|
||||
]);
|
||||
}
|
||||
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => 'Invalid API key provided.',
|
||||
'error' => 'API_KEY_INVALID'
|
||||
], 401);
|
||||
}
|
||||
|
||||
// Log successful API key usage
|
||||
if (config('api_security.log_api_key_usage', true)) {
|
||||
Log::info('API key authenticated', [
|
||||
'ip' => $request->ip(),
|
||||
'user_agent' => $request->header('User-Agent'),
|
||||
'endpoint' => $request->fullUrl(),
|
||||
'method' => $request->method(),
|
||||
'api_key_prefix' => substr($apiKey, 0, 8) . '...',
|
||||
]);
|
||||
}
|
||||
|
||||
// Add API key info to request for downstream use
|
||||
$request->merge(['_api_key' => $apiKey]);
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract API key from request headers
|
||||
*/
|
||||
private function extractApiKey(Request $request): ?string
|
||||
{
|
||||
// Check multiple header formats
|
||||
$apiKeyHeaders = config('api_security.api_key_headers', [
|
||||
'X-API-Key',
|
||||
'API-Key',
|
||||
'Authorization'
|
||||
]);
|
||||
|
||||
foreach ($apiKeyHeaders as $header) {
|
||||
$value = $request->header($header);
|
||||
|
||||
if ($value) {
|
||||
// Handle Bearer token format
|
||||
if ($header === 'Authorization' && preg_match('/Bearer\s+(.*)$/i', $value, $matches)) {
|
||||
return $matches[1];
|
||||
}
|
||||
|
||||
// Direct API key
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate API key against configured valid keys
|
||||
*/
|
||||
private function isValidApiKey(string $apiKey): bool
|
||||
{
|
||||
$validApiKeys = config('api_security.valid_api_keys', []);
|
||||
|
||||
if (empty($validApiKeys)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return in_array($apiKey, $validApiKeys);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Support\AuthCookie;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class AuthenticateFromCookie
|
||||
{
|
||||
/**
|
||||
* Promote HttpOnly auth cookie to Authorization header for Sanctum.
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
if (! $request->bearerToken()) {
|
||||
$token = $request->cookie(AuthCookie::name());
|
||||
|
||||
if (is_string($token) && $token !== '') {
|
||||
$request->headers->set('Authorization', 'Bearer '.$token);
|
||||
}
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class BlockApiToolsMiddleware
|
||||
{
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
// Check if API tool blocking is enabled
|
||||
if (!config('api_security.block_api_tools_in_production')) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
// Skip blocking for external API routes - they use API key authentication
|
||||
if ($request->is('api/external*')) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
// Only block in production environment
|
||||
if (app()->environment('production')) {
|
||||
$userAgent = strtolower($request->header('User-Agent', ''));
|
||||
$clientIp = $request->ip();
|
||||
|
||||
// Check if request has valid API key - bypass blocking for external systems
|
||||
if ($this->hasValidApiKey($request)) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
// Check if IP is in allowed list
|
||||
$allowedIps = config('api_security.allowed_ips', []);
|
||||
if (!empty($allowedIps) && in_array($clientIp, $allowedIps)) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
// Check if User-Agent is in allowed list
|
||||
$allowedUserAgents = config('api_security.allowed_user_agents', []);
|
||||
foreach ($allowedUserAgents as $allowedAgent) {
|
||||
if (str_contains($userAgent, strtolower($allowedAgent))) {
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
|
||||
// Check if the User-Agent matches any blocked patterns
|
||||
$blockedUserAgents = config('api_security.blocked_user_agents', []);
|
||||
foreach ($blockedUserAgents as $blockedAgent) {
|
||||
if (str_contains($userAgent, $blockedAgent)) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => config('api_security.blocked_message', 'API access is restricted in production environment. Please use the web interface.'),
|
||||
'error' => 'API_TOOLS_BLOCKED'
|
||||
], 403);
|
||||
}
|
||||
}
|
||||
|
||||
// Additional check for requests without proper browser User-Agent
|
||||
// This catches tools that might not be in our list but don't look like browsers
|
||||
if ($this->isSuspiciousUserAgent($userAgent)) {
|
||||
return response()->json([
|
||||
'success' => false,
|
||||
'message' => config('api_security.blocked_message', 'API access is restricted in production environment. Please use the web interface.'),
|
||||
'error' => 'API_TOOLS_BLOCKED'
|
||||
], 403);
|
||||
}
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the User-Agent looks suspicious (not a real browser)
|
||||
*/
|
||||
private function isSuspiciousUserAgent(string $userAgent): bool
|
||||
{
|
||||
$minLength = config('api_security.min_user_agent_length', 10);
|
||||
|
||||
// If User-Agent is empty or very short, it's suspicious
|
||||
if (empty($userAgent) || strlen($userAgent) < $minLength) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check for common browser patterns
|
||||
$browserPatterns = [
|
||||
'mozilla',
|
||||
'chrome',
|
||||
'safari',
|
||||
'firefox',
|
||||
'edge',
|
||||
'opera',
|
||||
'webkit',
|
||||
'gecko',
|
||||
'trident',
|
||||
'msie',
|
||||
];
|
||||
|
||||
$hasBrowserPattern = false;
|
||||
foreach ($browserPatterns as $pattern) {
|
||||
if (str_contains($userAgent, $pattern)) {
|
||||
$hasBrowserPattern = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// If no browser pattern is found, it's likely an API tool
|
||||
return !$hasBrowserPattern;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the request has a valid API key for external system access
|
||||
*/
|
||||
private function hasValidApiKey(Request $request): bool
|
||||
{
|
||||
// Check for API key in headers (X-API-Key, Authorization Bearer, or API-Key)
|
||||
$apiKey = $request->header('X-API-Key')
|
||||
?? $request->header('API-Key')
|
||||
?? $this->extractBearerToken($request->header('Authorization'));
|
||||
|
||||
if (!$apiKey) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Get valid API keys from configuration
|
||||
$validApiKeys = config('api_security.valid_api_keys', []);
|
||||
|
||||
// If no API keys configured, return false
|
||||
if (empty($validApiKeys)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if the provided API key is valid
|
||||
return in_array($apiKey, $validApiKeys);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract Bearer token from Authorization header
|
||||
*/
|
||||
private function extractBearerToken(?string $authorization): ?string
|
||||
{
|
||||
if (!$authorization) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (preg_match('/Bearer\s+(.*)$/i', $authorization, $matches)) {
|
||||
return $matches[1];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Support\AuthCookie;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Laravel\Sanctum\PersonalAccessToken;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Modules\Auth\Entities\User;
|
||||
|
||||
class SingleSessionMiddleware
|
||||
{
|
||||
/**
|
||||
* Cache TTL for token processing lock (seconds)
|
||||
*/
|
||||
private const PROCESSING_LOCK_TTL = 5;
|
||||
|
||||
/**
|
||||
* Cache TTL for token name cache (seconds)
|
||||
*/
|
||||
private const TOKEN_NAME_CACHE_TTL = 60;
|
||||
|
||||
/**
|
||||
* Fresh token age threshold (seconds)
|
||||
*/
|
||||
private const FRESH_TOKEN_AGE = 30;
|
||||
|
||||
/**
|
||||
* Handle an incoming request.
|
||||
*
|
||||
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
|
||||
*/
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$user = $request->user();
|
||||
|
||||
if ($user) {
|
||||
try {
|
||||
$this->enforceSingleSession($user, $request);
|
||||
} catch (\Throwable $e) {
|
||||
// Log error but don't block the request
|
||||
Log::error('SingleSessionMiddleware error', [
|
||||
'user_id' => $user->id,
|
||||
'error' => $e->getMessage(),
|
||||
'trace' => $e->getTraceAsString()
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Enforce single session per user
|
||||
*/
|
||||
private function enforceSingleSession(User $user, Request $request): void
|
||||
{
|
||||
if (app()->environment('local')) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip single session enforcement during impersonation
|
||||
if ($this->isImpersonationRequest($request)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip single session enforcement for post-impersonation requests
|
||||
if ($this->isPostImpersonationRequest($request)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get current token from request (Bearer header or HttpOnly cookie)
|
||||
$currentToken = $this->resolveToken($request);
|
||||
if (!$currentToken) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse the token to get the token ID and hash
|
||||
$tokenParts = explode('|', $currentToken);
|
||||
if (count($tokenParts) !== 2) {
|
||||
return;
|
||||
}
|
||||
|
||||
$tokenId = $tokenParts[0];
|
||||
$tokenHash = $tokenParts[1];
|
||||
|
||||
// Find current token record with caching
|
||||
$currentTokenRecord = $this->getTokenRecord($tokenId, $tokenHash);
|
||||
|
||||
if (!$currentTokenRecord) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if this is an impersonation token - skip enforcement
|
||||
if ($currentTokenRecord->name === 'impersonation-token') {
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip enforcement for fresh login tokens (SSO login or fresh auth-token)
|
||||
if ($this->isFreshLoginToken($currentTokenRecord, $user)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Use atomic cache lock per user to prevent race conditions
|
||||
$lockKey = "single_session_user_{$user->id}";
|
||||
$lock = Cache::lock($lockKey, self::PROCESSING_LOCK_TTL);
|
||||
|
||||
if (!$lock->get()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Get all active tokens for this user (excluding impersonation), ordered by newest first
|
||||
$activeTokens = PersonalAccessToken::where('tokenable_type', get_class($user))
|
||||
->where('tokenable_id', $user->id)
|
||||
->where('name', '!=', 'impersonation-token')
|
||||
->where(function ($query) {
|
||||
$query->whereNull('expires_at')
|
||||
->orWhere('expires_at', '>', now());
|
||||
})
|
||||
->orderByDesc('created_at')
|
||||
->orderByDesc('id')
|
||||
->get();
|
||||
|
||||
// Keep only the most recently created token (latest login); revoke all others
|
||||
if ($activeTokens->count() > 1) {
|
||||
$latestToken = $activeTokens->first();
|
||||
$idsToDelete = $activeTokens->where('id', '!=', $latestToken->id)->pluck('id');
|
||||
|
||||
PersonalAccessToken::whereIn('id', $idsToDelete)->delete();
|
||||
|
||||
$this->notifyConcurrentSession($user, $request);
|
||||
}
|
||||
} finally {
|
||||
$lock->release();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get token record with caching
|
||||
*/
|
||||
private function getTokenRecord(string $tokenId, string $tokenHash): ?PersonalAccessToken
|
||||
{
|
||||
$cacheKey = "token_record_{$tokenId}";
|
||||
|
||||
return Cache::remember($cacheKey, self::TOKEN_NAME_CACHE_TTL, function () use ($tokenId, $tokenHash) {
|
||||
return PersonalAccessToken::where('id', $tokenId)
|
||||
->where('token', hash('sha256', $tokenHash))
|
||||
->first();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this is an impersonation-related request
|
||||
*/
|
||||
private function isImpersonationRequest(Request $request): bool
|
||||
{
|
||||
$path = $request->path();
|
||||
|
||||
// Check if the request is to impersonation endpoints
|
||||
if (str_contains($path, 'impersonate')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check if there's an impersonation header
|
||||
if ($request->hasHeader('X-Original-User-Id')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check if the request has impersonation token
|
||||
$currentToken = $this->resolveToken($request);
|
||||
if ($currentToken) {
|
||||
$tokenParts = explode('|', $currentToken);
|
||||
if (count($tokenParts) === 2) {
|
||||
$tokenId = $tokenParts[0];
|
||||
$tokenHash = $tokenParts[1];
|
||||
|
||||
// Use cached token record to avoid duplicate queries
|
||||
$tokenRecord = $this->getTokenRecord($tokenId, $tokenHash);
|
||||
|
||||
if ($tokenRecord && $tokenRecord->name === 'impersonation-token') {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this is a post-impersonation request (after leaving impersonation)
|
||||
*/
|
||||
private function isPostImpersonationRequest(Request $request): bool
|
||||
{
|
||||
$path = $request->path();
|
||||
|
||||
// Check if this is a request after leaving impersonation
|
||||
// Look for requests that have X-Original-User-Id header but are not impersonation endpoints
|
||||
if ($request->hasHeader('X-Original-User-Id') && !str_contains($path, 'impersonate')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the current token is a fresh login token (SSO login or post-impersonation)
|
||||
* This prevents false positives when a user legitimately logs in
|
||||
*/
|
||||
private function isFreshLoginToken(PersonalAccessToken $currentTokenRecord, User $user): bool
|
||||
{
|
||||
// Check if token was created recently (within threshold)
|
||||
$tokenAge = $currentTokenRecord->created_at->diffInSeconds(now());
|
||||
|
||||
if ($tokenAge > self::FRESH_TOKEN_AGE) {
|
||||
return false; // Token is not fresh
|
||||
}
|
||||
|
||||
// For SSO tokens, if they're fresh, skip enforcement (legitimate login)
|
||||
if ($currentTokenRecord->name === 'sso-token') {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check for both 'authToken' (camelCase - regular login) and 'auth-token' (kebab-case - post-impersonation)
|
||||
$isAuthToken = in_array($currentTokenRecord->name, ['authToken', 'auth-token'], true);
|
||||
|
||||
if ($isAuthToken) {
|
||||
// Check if there are any other auth tokens for this user that were created before this one
|
||||
// When logging out properly, all tokens should be deleted, so if there are no older
|
||||
// auth tokens, this is likely a fresh login or post-impersonation
|
||||
$olderAuthTokens = PersonalAccessToken::where('tokenable_type', get_class($user))
|
||||
->where('tokenable_id', $user->id)
|
||||
->where('id', '!=', $currentTokenRecord->id)
|
||||
->whereIn('name', ['authToken', 'auth-token']) // Check for both naming conventions
|
||||
->where('created_at', '<', $currentTokenRecord->created_at)
|
||||
->where(function ($query) {
|
||||
$query->whereNull('expires_at')
|
||||
->orWhere('expires_at', '>', now());
|
||||
})
|
||||
->exists(); // Use exists() instead of count() for better performance
|
||||
|
||||
// If there are no older auth tokens, this is a fresh login or post-impersonation
|
||||
if (!$olderAuthTokens) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify user about concurrent session
|
||||
*/
|
||||
private function notifyConcurrentSession(User $user, Request $request): void
|
||||
{
|
||||
// Notification creation removed per user request
|
||||
// Concurrent session detection still works, but no notification is created
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve Sanctum plain-text token from Authorization header or auth cookie.
|
||||
*/
|
||||
private function resolveToken(Request $request): ?string
|
||||
{
|
||||
$token = $request->bearerToken();
|
||||
|
||||
if (is_string($token) && $token !== '') {
|
||||
return $token;
|
||||
}
|
||||
|
||||
$cookieToken = $request->cookie(AuthCookie::name());
|
||||
|
||||
return is_string($cookieToken) && $cookieToken !== '' ? $cookieToken : null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user