Security
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)
Multi-Layer Security Architecture
Security Flow
Every request flows through 8 layers of security protection:
Legend:
- ✅ AUTOMATIC - Enabled by default, no developer action needed
- ⚙️ Developer Calls - Available methods developers use in their code
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"
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 <script>alert('XSS')</script>
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:
<script>alert('XSS')</script>
How It Works:
GEMVC uses FILTER_SANITIZE_FULL_SPECIAL_CHARS to HTML-entity encode all special characters. This means < becomes <, preventing script execution in browsers.
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.,
idmust beint, not"1' OR '1'='1") - Missing Fields: Ensures required fields are present
- Invalid Formats: Validates email, URL, date formats
<?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"
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_SECRETfrom.env - ✓ Expiration Validation - Checks
exp > time() - ✓ Role-Based Access Control - Multi-role support
- ✓ Token Renewal - Built-in token renewal mechanism
<?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"
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.
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.
<?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()andauth()in your API services - ✓ Zero configuration - Security works out of the box!
Security Best Practices
💡 Always Use Schema Validation
<?php
if (!$this->request->definePostSchema(['email' => 'email'])) {
return $this->request->returnResponse();
}
<?php
$email = $this->request->post['email']; // No validation!
💡 Always Use Authentication
<?php
if (!$this->request->auth(['admin'])) {
return $this->request->returnResponse();
}
<?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()ordefineGetSchema()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()!