$npx -y skills add edutrul/drupal-ai --skill drupal-securityDrupal security for routes, controllers, forms, and queries. Add route permissions, access checks, CSRF protection, XSS prevention, SQL injection prevention, and secure file upload validation.
| 1 | # Drupal Security |
| 2 | |
| 3 | ## Critical Security Patterns |
| 4 | |
| 5 | ### SQL Injection Prevention |
| 6 | |
| 7 | **NEVER concatenate user input into queries:** |
| 8 | |
| 9 | ```php |
| 10 | // VULNERABLE - SQL injection |
| 11 | $query = "SELECT * FROM users WHERE name = '" . $name . "'"; |
| 12 | $result = $connection->query($query); |
| 13 | |
| 14 | // SAFE - parameterized query |
| 15 | $result = $connection->select('users', 'u') |
| 16 | ->fields('u') |
| 17 | ->condition('name', $name) |
| 18 | ->execute(); |
| 19 | |
| 20 | // SAFE - placeholder |
| 21 | $result = $connection->query( |
| 22 | 'SELECT * FROM {users} WHERE name = :name', |
| 23 | [':name' => $name] |
| 24 | ); |
| 25 | ``` |
| 26 | |
| 27 | ### XSS Prevention |
| 28 | |
| 29 | **Always escape output. Trust the render system:** |
| 30 | |
| 31 | ```php |
| 32 | // VULNERABLE - raw HTML output |
| 33 | return ['#markup' => $user_input]; |
| 34 | return ['#markup' => '<div>' . $title . '</div>']; |
| 35 | |
| 36 | // SAFE - plain text (auto-escaped) |
| 37 | return ['#plain_text' => $user_input]; |
| 38 | |
| 39 | // SAFE - use proper render elements |
| 40 | return [ |
| 41 | '#type' => 'html_tag', |
| 42 | '#tag' => 'div', |
| 43 | '#value' => $title, // Escaped automatically |
| 44 | ]; |
| 45 | |
| 46 | // SAFE - Twig auto-escapes |
| 47 | {{ variable }} // Escaped |
| 48 | {{ variable|raw }} // DANGEROUS - only for trusted HTML |
| 49 | ``` |
| 50 | |
| 51 | **For admin-only content:** |
| 52 | ```php |
| 53 | use Drupal\Component\Utility\Xss; |
| 54 | |
| 55 | // Filter but allow safe HTML tags |
| 56 | $safe = Xss::filterAdmin($user_html); |
| 57 | ``` |
| 58 | |
| 59 | Note: Never pass untrusted user input into `#markup`. Prefer `#plain_text`, Twig auto-escaping, or safe render elements. |
| 60 | |
| 61 | ### Access Control |
| 62 | |
| 63 | **Always verify permissions:** |
| 64 | |
| 65 | ```php |
| 66 | // In routing.yml |
| 67 | my_module.admin: |
| 68 | path: '/admin/my-module' |
| 69 | requirements: |
| 70 | _permission: 'administer my_module' # Required! |
| 71 | |
| 72 | // In code |
| 73 | if (!$this->currentUser->hasPermission('administer my_module')) { |
| 74 | throw new AccessDeniedHttpException(); |
| 75 | } |
| 76 | |
| 77 | // Entity queries - check access! |
| 78 | $query = $this->entityTypeManager |
| 79 | ->getStorage('node') |
| 80 | ->getQuery() |
| 81 | ->accessCheck(TRUE) // CRITICAL - never FALSE unless intentional |
| 82 | ->condition('type', 'article'); |
| 83 | ``` |
| 84 | |
| 85 | ### CSRF Protection |
| 86 | |
| 87 | Forms automatically include CSRF tokens. For custom AJAX: |
| 88 | |
| 89 | ```php |
| 90 | // Include token in AJAX requests |
| 91 | $build['#attached']['drupalSettings']['myModule']['token'] = |
| 92 | \Drupal::csrfToken()->get('my_module_action'); |
| 93 | ``` |
| 94 | Note: Prefer dependency injection over direct `\Drupal::service()` or `\Drupal::` calls in classes. |
| 95 | |
| 96 | ```php |
| 97 | // Validate in controller |
| 98 | if (!$this->csrfToken->validate($token, 'my_module_action')) { |
| 99 | throw new AccessDeniedHttpException('Invalid token'); |
| 100 | } |
| 101 | ``` |
| 102 | |
| 103 | ### File Upload Security |
| 104 | |
| 105 | ```php |
| 106 | $validators = [ |
| 107 | 'file_validate_extensions' => ['pdf doc docx'], // Whitelist extensions |
| 108 | 'file_validate_size' => [25600000], // 25MB limit |
| 109 | 'FileSecurity' => [], // Drupal 10.2+ - blocks dangerous files |
| 110 | ]; |
| 111 | |
| 112 | // NEVER trust file extension alone - check MIME type |
| 113 | $file_mime = $file->getMimeType(); |
| 114 | $allowed_mimes = ['application/pdf', 'application/msword']; |
| 115 | if (!in_array($file_mime, $allowed_mimes)) { |
| 116 | // Reject file |
| 117 | } |
| 118 | ``` |
| 119 | |
| 120 | ### Sensitive Data |
| 121 | |
| 122 | ```php |
| 123 | // NEVER log sensitive data |
| 124 | $this->logger->info('User @user logged in', ['@user' => $username]); |
| 125 | // NOT: $this->logger->info('Login: ' . $username . ':' . $password); |
| 126 | |
| 127 | // NEVER expose in error messages |
| 128 | throw new \Exception('Database error'); // Generic |
| 129 | // NOT: throw new \Exception('Query failed: ' . $query); |
| 130 | |
| 131 | // Use environment variables for secrets |
| 132 | $api_key = getenv('MY_API_KEY'); |
| 133 | // NOT: $api_key = 'hardcoded-secret-key'; |
| 134 | ``` |
| 135 | |
| 136 | ## Red Flags to Watch For |
| 137 | |
| 138 | When you see these patterns, **immediately warn**: |
| 139 | |
| 140 | | Pattern | Risk | Fix | |
| 141 | |---------|------|-----| |
| 142 | | String concatenation in SQL | SQL injection | Use query builder | |
| 143 | | `#markup` with variables | XSS | Use `#plain_text` | |
| 144 | | `accessCheck(FALSE)` | Access bypass | Use `accessCheck(TRUE)` | |
| 145 | | Missing `_permission` in routes | Unauthorized access | Add permission | |
| 146 | | Custom controller with no access check | Unauthorized access | Add route permission or access callback | |
| 147 | | `{{ var\|raw }}` in Twig | XSS | Remove `\|raw` | |
| 148 | | Hardcoded passwords/keys | Credential exposure | Use env vars | |
| 149 | | `eval()` or `exec()` | Code injection | Avoid entirely | |
| 150 | | `unserialize()` on user data | Object injection | Use JSON | |
| 151 | | Missing CSRF validation in custom endpoints | CSRF attack | Validate token using csrf_token service | |
| 152 | | File upload without validation | Malicious file upload | Validate extension, size, and MIME type | |
| 153 | | Direct `\Drupal::` usage in classes | Hard to test / bad practice | Use dependency injection | |
| 154 | | Logging sensitive data | Information disclosure | Mask or avoid logging sensitive fields | |