Trust nothing. Verify everything.
Traditional security assumed that anything inside the corporate network was safe. But cloud computing, remote work, and microservices have destroyed the perimeter. Zero-Trust Architecture assumes breach β every request could be from an attacker. You authenticate, authorize, and encrypt everything, every time.
| Pillar | Description | Implementation |
|---|---|---|
| 1. Identity Verification | Every user and service has a unique identity | OAuth2, OIDC, JWT, API keys, mTLS |
| 2. Device Verification | Only authorized devices can connect | Device certificates, MDM, hardware attestation |
| 3. Least Privilege Access | Only the minimum necessary access | Just-in-time (JIT) access, short-lived tokens |
| 4. Micro-segmentation | Network is broken into small zones | Service mesh (Istio), network policies |
| 5. Continuous Monitoring | Every access is logged and analyzed | SIEM, UEBA, real-time anomaly detection |
// routes/api.php - Even internal services must authenticate
Route::middleware(['auth:sanctum', 'throttle:api'])->group(function () {
Route::get('/internal/users', [UserController::class, 'index']);
Route::post('/internal/orders', [OrderController::class, 'store']);
});
// Service-to-service authentication using API tokens
class InternalApiMiddleware
{
public function handle($request, $next)
{
$token = $request->header('X-Service-Token');
if (!$token || !ServiceToken::where('token', hash('sha256', $token))->exists()) {
return response()->json(['error' => 'Unauthorized'], 401);
}
// Also check if the service is allowed to access this endpoint
$service = ServiceToken::where('token', hash('sha256', $token))->first();
if (!$service->canAccess($request->path())) {
return response()->json(['error' => 'Forbidden'], 403);
}
$request->merge(['service_name' => $service->name]);
return $next($request);
}
}
// JWT with short expiry (15 minutes)
use Tymon\JWTAuth\Facades\JWTAuth;
$token = JWTAuth::customClaims([
'exp' => now()->addMinutes(15)->timestamp,
'service' => 'order-service',
'permissions' => ['read:users', 'write:orders'],
])->fromUser($serviceAccount);
// Client MUST refresh before expiry
// No long-lived secrets stored in code
# Nginx configuration for mTLS
server {
listen 443 ssl;
ssl_certificate /etc/nginx/certs/server.crt;
ssl_certificate_key /etc/nginx/certs/server.key;
# Client certificate validation
ssl_client_certificate /etc/nginx/certs/ca.crt;
ssl_verify_client on;
location / {
# Only allow requests with valid client certificates
if ($ssl_client_verify != SUCCESS) {
return 403;
}
proxy_pass http://laravel;
}
}
-- Create separate database users for each service
CREATE USER 'order_service'@'%' IDENTIFIED BY '...';
GRANT SELECT, INSERT, UPDATE ON mydb.orders TO 'order_service'@'%';
GRANT SELECT ON mydb.users TO 'order_service'@'%';
-- NO DELETE, NO ALTER, NO DROP
CREATE USER 'user_service'@'%' IDENTIFIED BY '...';
GRANT SELECT, INSERT, UPDATE ON mydb.users TO 'user_service'@'%';
-- NO access to orders table
# Laravel config for different services
# config/database.php
'connections' => [
'order_db' => [
'username' => 'order_service', // Limited permissions
'password' => env('ORDER_DB_PASSWORD'),
],
'user_db' => [
'username' => 'user_service', // Different user!
'password' => env('USER_DB_PASSWORD'),
],
],
# Deny all ingress by default
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-ingress
spec:
podSelector: {}
policyTypes:
- Ingress
# Allow frontend to call api-gateway
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-frontend-to-api
spec:
podSelector:
matchLabels:
app: api-gateway
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- port: 8080
Don't ask "Did we get hacked?" Ask "When did we get hacked, and what did they access?" Assume attackers are already inside.
// Log EVERY access (for audit)
class SecurityLogger
{
public function logAccess($userId, $resource, $action, $result)
{
Log::channel('security')->info('Access attempt', [
'user_id' => $userId,
'resource' => $resource,
'action' => $action,
'result' => $result,
'ip' => request()->ip(),
'user_agent' => request()->userAgent(),
'timestamp' => microtime(true),
]);
}
}
// Detect anomalies (simplified)
class AnomalyDetector
{
public function check($userId, $action)
{
$recentRequests = Cache::get("user:{$userId}:requests", []);
$recentRequests[] = ['action' => $action, 'time' => time()];
Cache::put("user:{$userId}:requests", $recentRequests, 300);
// Check for rate anomalies
if (count($recentRequests) > 100) {
Log::channel('security')->alert("Rate anomaly for user {$userId}");
}
// Check for time anomalies (access at 3 AM)
if (date('H') < 5 && $this->userUsuallyWorksAtNight($userId) === false) {
Log::channel('security')->alert("Time anomaly for user {$userId}");
}
}
}
// Temporary access token
class JITAccess
{
public function requestAccess(string $userId, string $resource, int $durationMinutes = 60)
{
$token = JITToken::create([
'user_id' => $userId,
'resource' => $resource,
'expires_at' => now()->addMinutes($durationMinutes),
'reason' => request('reason'),
'approved_by' => auth()->id(),
]);
return $token;
}
public function checkAccess(string $userId, string $resource)
{
$token = JITToken::where('user_id', $userId)
->where('resource', $resource)
->where('expires_at', '>', now())
->first();
if (!$token) {
Log::channel('security')->warning("Unauthorized access attempt", [
'user' => $userId,
'resource' => $resource,
]);
throw new UnauthorizedException("No JIT access for this resource");
}
return true;
}
}
An attacker with a valid API key can run up huge bills by requesting expensive operations (large reports, image processing, AI calls). Zero-Trust includes protecting your wallet.
// API rate limiting per key
Route::middleware(['throttle:1000,60'])->group(function () {
// 1000 requests per minute per API key
});
// Cost-based rate limiting
class CostBasedRateLimiter
{
public function check($apiKey, $operationCost)
{
$dailyCost = Cache::get("api:{$apiKey}:daily_cost", 0);
$dailyBudget = 10.00; // $10 per day
if ($dailyCost + $operationCost > $dailyBudget) {
Log::channel('security')->alert("API key {$apiKey} exceeded budget");
throw new BudgetExceededException("Daily budget exceeded");
}
Cache::increment("api:{$apiKey}:daily_cost", $operationCost);
Cache::expire("api:{$apiKey}:daily_cost", 86400);
return true;
}
}
// Usage
$cost = $this->calculateOperationCost($request);
$rateLimiter->check($request->api_key, $cost);
| Principle | Traditional Security | Zero-Trust |
|---|---|---|
| Network perimeter | Trust inside, distrust outside | No trusted network |
| Authentication | Once at the edge | Every request, every service |
| Authorization | Broad permissions | Least privilege, JIT access |
| Encryption | Only external traffic | Everywhere (mTLS) |
| Monitoring | Log breaches | Assume breach, constant monitoring |
The Performance Bible β Complete. You now have 30 topics covering everything from algorithms to zero-trust. This is not the end. This is the foundation. Every system you build will teach you something new. Keep learning. Keep optimizing. Keep architecting.
"The language is just a tool. You don't blame the hammer if you can't build a skyscraper alone."