Security

25 minutes INTERMEDIATE

Learn about GEMVC's comprehensive security architecture. Discover how 90% of security is automatic, protecting against XSS, SQL injection, path traversal, and more.

What You'll Learn

Automatic Security

90% of security is automatic - no configuration needed

Multi-Layer Protection

8 layers of security from request to database

Attack Prevention

Protection against XSS, SQL injection, path traversal, and more

Video Coming Soon...

GEMVC Security Overview

GEMVC is architected with security-by-design principles, implementing multi-layered defense mechanisms from request arrival to database operations. The most important point: 90% of GEMVC security is AUTOMATIC - no developer configuration needed!

🎯 Key Point:

90% of GEMVC security is AUTOMATIC - Security checks happen automatically in Bootstrap.php (Apache/Nginx) and SwooleBootstrap.php (OpenSwoole) for every request. Your app/api/ code never needs to worry about sanitization - it's already done!

  • Automatic Protection - Path access, header sanitization, input sanitization, SQL injection prevention
  • Multi-Layer Defense - 8 layers of security from request to database
  • Zero Configuration - Security works out of the box
  • Developer-Friendly - Simple method calls for remaining 10% (schema validation, authentication)
1

Multi-Layer Security Architecture

Security Flow

Every request flows through 8 layers of security protection:

1
Path Access Security
SecurityManager - Blocks direct file access
βœ… AUTOMATIC
2
Header Sanitization
ApacheRequest/SwooleRequest - Sanitizes all HTTP headers
βœ… AUTOMATIC
3
Input Sanitization
XSS Prevention - All inputs HTML-entity encoded
βœ… AUTOMATIC
4
Schema Validation
Request Filtering - Type checking, mass assignment prevention
βš™οΈ Developer Calls
5
Authentication & Authorization
JWT Token System - Role-based access control
βš™οΈ Developer Calls
6
File Security
Name/MIME sanitization, signature detection, encryption
βœ… AUTOMATIC + βš™οΈ
7
Business Logic Protection
Automatic protection in application code
βœ… AUTOMATIC
8
Database Security
SQL Injection Prevention - 100% prepared statements
βœ… AUTOMATIC

Legend:

  • βœ… AUTOMATIC - Enabled by default, no developer action needed
  • βš™οΈ Developer Calls - Available methods developers use in their code
2

Layer 1: Path Access Security

Automatic File Access Blocking

GEMVC automatically blocks direct access to sensitive application files and directories. This happens before any API code runs.

Blocked Paths:

  • βœ“ /app - Application code
  • βœ“ /vendor - Composer dependencies
  • βœ“ /bin - Executable files
  • βœ“ /templates - Template files
  • βœ“ /config - Configuration files
  • βœ“ /.env - Environment variables
  • βœ“ /.git - Version control

Attack Prevention:

❌ Attack:

GET /app/api/User.php

βœ… Result:

403 Forbidden - "Direct file access is not permitted"
3

Layer 2: Header Sanitization

Automatic Header Protection

All HTTP headers are automatically sanitized in Request constructors to prevent header injection and XSS attacks.

Sanitized Headers:

  • βœ“ HTTP_AUTHORIZATION - Sanitized before JWT extraction
  • βœ“ HTTP_USER_AGENT - Sanitized before logging
  • βœ“ HTTP_X_FORWARDED_FOR - Sanitized for security
  • βœ“ All custom headers (HTTP_*) - Automatically sanitized

Attack Prevention:

❌ Attack:

Authorization: Bearer <script>alert('XSS')</script>

βœ… Sanitized:

Authorization: Bearer &lt;script&gt;alert('XSS')&lt;/script&gt;
4

Layer 3: Input Sanitization (XSS Prevention)

Automatic XSS Protection

All inputs are automatically sanitized when the Request object is created. This prevents XSS (Cross-Site Scripting) attacks by HTML-entity encoding all special characters.

What Gets Sanitized:

  • βœ“ All POST data
  • βœ“ All GET parameters
  • βœ“ All PUT/PATCH data
  • βœ“ All HTTP headers
  • βœ“ Query strings
  • βœ“ Request URIs
  • βœ“ File names and MIME types

XSS Attack Prevention:

❌ Attack Input:

<script>alert('XSS')</script>

βœ… Sanitized Output:

&lt;script&gt;alert('XSS')&lt;/script&gt;

How It Works:

GEMVC uses FILTER_SANITIZE_FULL_SPECIAL_CHARS to HTML-entity encode all special characters. This means < becomes &lt;, preventing script execution in browsers.

5

Layer 4: Schema Validation

Request Filtering & Type Validation

Schema validation is the only layer that requires developer action. Use definePostSchema() or defineGetSchema() to validate requests before business logic execution.

What Schema Validation Prevents:

  • Mass Assignment: Prevents unwanted fields (e.g., is_admin: true)
  • Type Confusion: Validates data types (e.g., id must be int, not "1' OR '1'='1")
  • Missing Fields: Ensures required fields are present
  • Invalid Formats: Validates email, URL, date formats
app/api/Product.php - Schema Validation Example
<?php
public function create(): JsonResponse
{
    // Schema validation prevents attacks!
    if (!$this->request->definePostSchema([
        'name' => 'string',      // Required string
        'price' => 'float',      // Required float
        '?description' => 'string' // Optional string
    ])) {
        return $this->request->returnResponse(); // 400 Bad Request
    }
    
    // βœ… Only valid requests reach here!
    return (new ProductController($this->request))->create();
}

Attack Prevention Examples:

Attack 1: Mass Assignment

Request: {"name": "Product", "price": 99.99, "is_admin": true}

Result: ❌ REJECTED - "Unwanted post field: is_admin"

Attack 2: Type Confusion

Request: {"id": "1' OR '1'='1", "name": "Product"}

Schema: ['id' => 'int']

Result: ❌ REJECTED - "Invalid value for field id, expected type: int"

6

Layer 5: Authentication & Authorization

JWT Token System

GEMVC includes a built-in JWT (JSON Web Token) authentication system. Use $request->auth() to verify tokens and implement role-based access control.

Security Features:

  • βœ“ HS256 Signature - Uses TOKEN_SECRET from .env
  • βœ“ Expiration Validation - Checks exp > time()
  • βœ“ Role-Based Access Control - Multi-role support
  • βœ“ Token Renewal - Built-in token renewal mechanism
app/api/Product.php - Authentication Example
<?php
public function create(): JsonResponse
{
    // Authentication check
    if (!$this->request->auth()) {
        return $this->request->returnResponse(); // 401 Unauthorized
    }
    
    // Authorization check (role-based)
    if (!$this->request->auth(['admin', 'salesManager'])) {
        return $this->request->returnResponse(); // 403 Forbidden
    }
    
    // βœ… Authenticated and authorized
    return (new ProductController($this->request))->create();
}

Attack Prevention:

Attack: Forged Token

Result: ❌ REJECTED - "Invalid JWT token. Authentication failed"

Attack: Role Escalation

Token: role="user", Request requires role="admin"

Result: ❌ REJECTED - "Role user not allowed to perform this action"

7

Layer 6: File Security

File Upload Protection

GEMVC provides multiple layers of file security: automatic name/MIME sanitization, signature detection, and optional encryption.

Automatic: File Name & MIME Sanitization

File names and MIME types are automatically sanitized in Request constructors to prevent path traversal and MIME injection attacks.

File Signature Detection (Magic Bytes)

Use ImageHelper::convertToWebP() to validate actual file signatures, not just file extensions or MIME types.

Prevents: Double extension attacks (malware.php.jpg), MIME spoofing, PHP files renamed to images

File Encryption

Use FileHelper::encrypt() for AES-256-CBC encryption with HMAC-SHA256 integrity verification.

8

Layer 8: Database Security (SQL Injection Prevention)

100% Prepared Statements

GEMVC automatically enforces prepared statements for ALL database queries. SQL injection is impossible because all queries use parameter binding, not string concatenation.

How It Works:

All queries use PDO::prepare() and bindValue(). The database treats all input as literal values, not SQL code.

ProductTable.php - SQL Injection Prevention
<?php
// All queries use prepared statements automatically
$products = (new ProductTable())
    ->select('id,name,price')
    ->where('name', "Product'; DROP TABLE products; --")  // Malicious input
    ->run();

// Generated SQL:
// SELECT id,name,price FROM products WHERE name = :name
// Bound: [':name' => "Product'; DROP TABLE products; --"]

// Database Execution:
// SELECT id,name,price FROM products WHERE name = 'Product'; DROP TABLE products; --'
// Database treats entire string as literal value, NOT SQL code!

// Result: βœ… SQL INJECTION PREVENTED
// No matching product found (as expected)

Attack Prevention:

Attack: SQL Injection

Input: "admin' OR '1'='1"

Result: βœ… PREVENTED - Database treats as literal string, not SQL code

Attack Prevention Matrix

Attack Type Attack Vector GEMVC Protection Result
XSS <script>alert('XSS')</script> Input sanitization βœ… Prevented
SQL Injection admin' OR '1'='1 Prepared statements βœ… Prevented
Path Traversal ../../../etc/passwd Path blocking + filename sanitization βœ… Prevented
File Upload malware.php.jpg Signature detection βœ… Prevented
Mass Assignment {is_admin: true} Schema validation βœ… Prevented
JWT Forgery Modified token Signature verification βœ… Prevented
Role Escalation User accessing admin endpoint Authorization check βœ… Prevented

Security Guarantees

βœ… Automatic Protection (No Developer Action Needed)

GEMVC provides automatic protection against:

  • βœ“ XSS (Cross-Site Scripting) - Input sanitization + output encoding
  • βœ“ SQL Injection - Prepared statements (100% coverage)
  • βœ“ Path Traversal - Path blocking + filename sanitization
  • βœ“ Header Injection - Header sanitization
  • βœ“ File Upload Attacks - File name/MIME sanitization
  • βœ“ JWT Forgery - Signature verification + expiration

βš™οΈ Developer-Enabled Protection (Simple Method Calls)

The remaining 10% requires simple method calls:

  • βœ“ Mass Assignment - Call definePostSchema()
  • βœ“ Type Confusion - Call definePostSchema()
  • βœ“ Authentication Bypass - Call $request->auth()
  • βœ“ Authorization Bypass - Call $request->auth(['role'])
  • βœ“ File Signature Spoofing - Use ImageHelper::convertToWebP()

πŸ“Š Result

  • βœ“ 90% of security is AUTOMATIC - No developer action needed!
  • βœ“ 10% requires simple method calls - Just use definePostSchema() and auth() in your API services
  • βœ“ Zero configuration - Security works out of the box!

Security Best Practices

πŸ’‘ Always Use Schema Validation

βœ… GOOD - Validate before processing
<?php
if (!$this->request->definePostSchema(['email' => 'email'])) {
    return $this->request->returnResponse();
}
❌ BAD - Process without validation
<?php
$email = $this->request->post['email']; // No validation!

πŸ’‘ Always Use Authentication

βœ… GOOD - Check authentication
<?php
if (!$this->request->auth(['admin'])) {
    return $this->request->returnResponse();
}
❌ BAD - No authentication check
<?php
// Anyone can access!

πŸ’‘ Prepared Statements (Automatic!)

GEMVC automatically enforces prepared statements for all database queries. SQL injection is impossible because all queries use parameter binding, not string concatenation.

Important Notes

  • 90% Automatic: Most security features work automatically - no configuration needed!
  • Schema Validation: Always use definePostSchema() or defineGetSchema() to validate requests.
  • Authentication: Always use $request->auth() to protect sensitive endpoints.
  • SQL Injection: Impossible in GEMVC - all queries use prepared statements automatically.
  • File Uploads: Use ImageHelper::convertToWebP() to validate file signatures, not just extensions.

πŸ”’ Security Mastered!

Excellent! You've learned about GEMVC's comprehensive security architecture. Remember: 90% of security is automatic, and the remaining 10% requires simple method calls like definePostSchema() and auth()!