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()!