diff --git a/.cursor/rules/accessibility-standards.mdc b/.cursor/rules/accessibility-standards.mdc
index 7729123..27b0876 100644
--- a/.cursor/rules/accessibility-standards.mdc
+++ b/.cursor/rules/accessibility-standards.mdc
@@ -6,7 +6,7 @@ globs: *.vue, *.jsx, *.tsx, *.html, *.php
Ensures WCAG compliance and accessibility best practices.
-
+```yaml
name: accessibility_standards
description: Enforce accessibility standards and WCAG compliance
filters:
@@ -18,7 +18,7 @@ actions:
conditions:
- pattern: "
]+(?!alt=)[^>]*>"
message: "Images must have alt attributes for screen readers."
-
+
- pattern: "aria-[a-z]+=\"\""
message: "ARIA attributes should not be empty; provide meaningful values."
@@ -53,4 +53,5 @@ actions:
metadata:
priority: high
version: 1.1
-
\ No newline at end of file
+```
+
diff --git a/.cursor/rules/api-standards.mdc b/.cursor/rules/api-standards.mdc
index 346d6e1..ade6b9d 100644
--- a/.cursor/rules/api-standards.mdc
+++ b/.cursor/rules/api-standards.mdc
@@ -6,7 +6,7 @@ globs: *.php, *.js, *.ts
Ensures consistent API design, documentation, and implementation best practices across PHP, JavaScript, and TypeScript files.
-
+```yaml
name: enhanced_api_standards
description: Enforce enhanced API design, implementation, and documentation standards
filters:
@@ -35,14 +35,14 @@ actions:
- **HTTP Methods:** Use proper HTTP methods for operations (GET for retrieval, POST for creation, etc.).
- **Status Codes:** Use appropriate HTTP status codes to communicate the result of the request.
- **Versioning:** Implement API versioning to manage changes without breaking existing integrations.
- - **Documentation:**
+ - **Documentation:**
- **Swagger/OpenAPI:** Use tools like Swagger for comprehensive API documentation.
- **Endpoint Descriptions:** Clearly document all endpoints including path, methods, parameters, and possible responses.
- **Authentication & Security:**
- Implement OAuth, JWT, or similar secure authentication methods.
- Use HTTPS for all API communications.
- **Rate Limiting:** Implement rate limiting to prevent abuse and ensure fair usage.
- - **Error Handling:**
+ - **Error Handling:**
- Provide clear, human-readable error messages with corresponding status codes.
- Implement error logging for debugging purposes.
- **Pagination:** For list endpoints, implement pagination to manage large datasets.
@@ -53,4 +53,5 @@ actions:
metadata:
priority: high
version: 1.1
-
\ No newline at end of file
+```
+
diff --git a/.cursor/rules/behat-ai-guide.mdc b/.cursor/rules/behat-ai-guide.mdc
index bd76ddc..81cb14f 100644
--- a/.cursor/rules/behat-ai-guide.mdc
+++ b/.cursor/rules/behat-ai-guide.mdc
@@ -73,7 +73,7 @@ class FeatureContext extends DrupalContext {
use PathTrait;
use ResponseTrait;
use WaitTrait;
-
+
// Drupal-specific traits
use BlockTrait;
use ContentTrait;
@@ -82,7 +82,7 @@ class FeatureContext extends DrupalContext {
use MediaTrait;
use TaxonomyTrait;
use UserTrait;
-
+
// Only add custom methods when drevops/behat-steps doesn't provide the functionality
}
```
@@ -212,9 +212,9 @@ The following is the complete reference from [drevops/behat-steps STEPS.md](http
[Source](vendor/drevops/behat-steps/src/DateTrait.php)
> Convert relative date expressions into timestamps or formatted dates.
->
+>
> Supports values and tables.
->
+>
> Possible formats:
> - `[relative:OFFSET]`
> - `[relative:OFFSET#FORMAT]`
@@ -298,7 +298,7 @@ The following is the complete reference from [drevops/behat-steps STEPS.md](http
>
> Skip processing with tags: `@behat-steps-skip:fileDownloadBeforeScenario` or
> `@behat-steps-skip:fileDownloadAfterScenario`
->
+>
> Special tags:
> - `@download` - enable download handling
@@ -418,9 +418,9 @@ The following is the complete reference from [drevops/behat-steps STEPS.md](http
[Source](vendor/drevops/behat-steps/src/Drupal/BigPipeTrait.php)
> Bypass Drupal BigPipe when rendering pages.
->
+>
> Activated by adding `@big_pipe` tag to the scenario.
->
+>
> Skip processing with tags: `@behat-steps-skip:bigPipeBeforeScenario` or
> `@behat-steps-skip:bigPipeBeforeStep`.
@@ -547,7 +547,7 @@ The following is the complete reference from [drevops/behat-steps STEPS.md](http
>
> Skip processing with tags: `@behat-steps-skip:emailBeforeScenario` or
> `@behat-steps-skip:emailAfterScenario`
->
+>
> Special tags:
> - `@email` - enable email tracking using a default handler
> - `@email:{type}` - enable email tracking using a `{type}` handler
@@ -756,10 +756,10 @@ Use `FileTrait` and `MediaTrait` from drevops/behat-steps along with built-in Dr
[Source](vendor/drevops/behat-steps/src/Drupal/TestmodeTrait.php)
> Configure Drupal Testmode module for controlled testing scenarios.
->
+>
> Skip processing with tags: `@behat-steps-skip:testmodeBeforeScenario` and
> `@behat-steps-skip:testmodeAfterScenario`.
->
+>
> Special tags:
> - `@testmode` - enable for scenario
@@ -810,7 +810,7 @@ Use `FileTrait` and `MediaTrait` from drevops/behat-steps along with built-in Dr
>
> Skip processing with tags: `@behat-steps-skip:watchdogSetScenario` or
> `@behat-steps-skip:watchdogAfterScenario`
->
+>
> Special tags:
> - `@watchdog:{type}` - limit watchdog messages to specific types.
> - `@error` - add to scenarios that are expected to trigger an error.
@@ -828,7 +828,7 @@ class FeatureContext extends DrupalContext {
use ContentTrait; // For content management
use UserTrait; // For user operations
use EmailTrait; // For email testing
-
+
// Custom methods only when absolutely necessary
}
```
diff --git a/.cursor/rules/build-optimization.mdc b/.cursor/rules/build-optimization.mdc
index 1ba1680..9a939a7 100644
--- a/.cursor/rules/build-optimization.mdc
+++ b/.cursor/rules/build-optimization.mdc
@@ -6,7 +6,7 @@ globs: webpack.config.js, vite.config.js, *.config.js
Ensures optimal build configuration and process for better performance and maintainability.
-
+```yaml
name: enhanced_build_optimization
description: Enforce standards for optimizing build processes
filters:
@@ -43,7 +43,7 @@ actions:
- **Caching:**
- Configure proper caching strategies (e.g., HTTP headers, service workers for PWA).
- Use long-term caching for static assets with content hashing in filenames.
- - **Modern JavaScript:**
+ - **Modern JavaScript:**
- Use ES6+ features but ensure polyfills for older browsers if needed.
- Consider using features like module/nomodule for graceful degradation.
- **Minification & Compression:** Ensure all JavaScript and CSS are minified and consider enabling gzip compression on the server.
@@ -54,4 +54,5 @@ actions:
metadata:
priority: high
version: 1.1
-
\ No newline at end of file
+```
+
diff --git a/.cursor/rules/code-generation-standards.mdc b/.cursor/rules/code-generation-standards.mdc
index a1689b4..898e132 100644
--- a/.cursor/rules/code-generation-standards.mdc
+++ b/.cursor/rules/code-generation-standards.mdc
@@ -6,7 +6,7 @@ globs: *.php, *.js, *.ts, *.vue, *.jsx, *.tsx, *.py
Ensures high-quality, executable code generation adhering to best practices across multiple programming languages.
-
+```yaml
name: enhanced_code_generation_standards
description: Enforce standards for code generation ensuring high quality and integration readiness
filters:
@@ -37,29 +37,29 @@ actions:
message: |
**Code Generation Best Practices:**
- **Executable Solutions:** Generate fully functional code, not just skeletons or stubs.
- - **Readability:**
+ - **Readability:**
- Prioritize code readability, with clear naming conventions and logical structure.
- Use whitespace effectively to enhance code clarity.
- - **Error Handling:**
+ - **Error Handling:**
- Implement comprehensive error handling with appropriate exceptions or error codes.
- Consider edge cases and provide meaningful error messages.
- - **Imports/Dependencies:**
+ - **Imports/Dependencies:**
- Include all necessary imports or require statements at the beginning of the file.
- Manage dependencies to ensure the code is self-contained or clearly documented for setup.
- - **Integration:**
+ - **Integration:**
- Code should be immediately usable within the project's existing framework or technology stack.
- Ensure compatibility with existing patterns or libraries used in the project.
- - **Formatting:**
+ - **Formatting:**
- Adhere to the project's coding style guide (e.g., Prettier, Black for Python, etc.).
- Use linters and formatters to maintain consistent code style.
- - **Testing:**
+ - **Testing:**
- Include unit or integration tests where applicable to validate generated code.
- Encourage test-driven development if part of the project's culture.
- - **Documentation:**
+ - **Documentation:**
- Provide inline comments for complex logic or algorithms.
- Write docstrings or JSDoc for functions, classes, and modules to describe usage, parameters, and return values.
- Consider generating external documentation if the project uses tools like Swagger for APIs or Sphinx for Python.
- - **Security:**
+ - **Security:**
- Avoid hardcoded credentials or sensitive information.
- Follow security best practices for the language (e.g., SQL injection prevention in PHP, XSS in JavaScript).
- **Performance:** While readability takes precedence, be mindful of performance implications of the generated code.
@@ -67,4 +67,5 @@ actions:
metadata:
priority: critical
version: 1.1
-
\ No newline at end of file
+```
+
diff --git a/.cursor/rules/cursor-rules.mdc b/.cursor/rules/cursor-rules.mdc
index b76782a..8d066cf 100644
--- a/.cursor/rules/cursor-rules.mdc
+++ b/.cursor/rules/cursor-rules.mdc
@@ -6,7 +6,7 @@ globs: *.mdc
Standards for placing and organizing Cursor rule files in the repository, ensuring rules are always up-to-date and follow best practices.
-
+```yaml
name: cursor_rules_location_and_maintenance
description: Standards for placing and maintaining Cursor rule files in the correct directory
filters:
@@ -15,7 +15,10 @@ filters:
pattern: "\\.mdc$"
# Match files that look like Cursor rules
- type: content
- pattern: "(?s).*?"
+ pattern: "(?s).*?
+```
+
+"
# Match file creation or modification events
- type: event
pattern: "file_create|file_modify"
@@ -63,13 +66,13 @@ actions:
filters:
- type: file_extension
pattern: "pattern_to_match"
-
+
actions:
- type: enforce|suggest|validate
conditions:
- pattern: "regex_pattern"
message: "Clear message explaining the issue"
-
+
metadata:
priority: high|medium|low
version: 1.0
@@ -111,7 +114,7 @@ examples:
# Good: Rule file in correct location
.cursor/rules/my-rule.mdc
output: "Correctly placed Cursor rule file"
-
+
- input: |
# Bad: Poorly structured rule
diff --git a/.cursor/rules/debugging-standards.mdc b/.cursor/rules/debugging-standards.mdc
index 4fb041f..e95a63d 100644
--- a/.cursor/rules/debugging-standards.mdc
+++ b/.cursor/rules/debugging-standards.mdc
@@ -6,7 +6,7 @@ globs: *.php, *.js, *.ts, *.vue, *.jsx, *.tsx, *.py
Ensures proper debugging practices and error handling.
-
+```yaml
name: debugging_standards
description: Enforce standards for debugging and error handling
filters:
@@ -36,4 +36,6 @@ actions:
metadata:
priority: high
version: 1.0
-
\ No newline at end of file
+```
+
+
diff --git a/.cursor/rules/docker-compose-standards.mdc b/.cursor/rules/docker-compose-standards.mdc
index 8bb85cd..697619a 100644
--- a/.cursor/rules/docker-compose-standards.mdc
+++ b/.cursor/rules/docker-compose-standards.mdc
@@ -1,9 +1,10 @@
---
description: Docker Compose standards Rule
-globs:
+globs:
alwaysApply: false
---
-
+
+```yaml
name: docker_compose_best_practices
description: Enforces best practices in docker-compose files to ensure maintainability, security, and consistency
filters:
@@ -136,4 +137,5 @@ examples:
metadata:
priority: high
version: 1.0
-
\ No newline at end of file
+```
+
diff --git a/.cursor/rules/drupal-authentication-failures.mdc b/.cursor/rules/drupal-authentication-failures.mdc
index c0ba535..1ea37bd 100644
--- a/.cursor/rules/drupal-authentication-failures.mdc
+++ b/.cursor/rules/drupal-authentication-failures.mdc
@@ -7,7 +7,7 @@ alwaysApply: false
This rule enforces security best practices to prevent identification and authentication failures in Drupal applications, as defined in OWASP Top 10:2021-A07.
-
+```yaml
name: drupal_authentication_failures
description: Detect and prevent identification and authentication failures in Drupal as defined in OWASP Top 10:2021-A07
filters:
@@ -22,39 +22,39 @@ actions:
# Pattern 1: Weak or missing password policies
- pattern: "UserPasswordConstraint|PasswordPolicy|user\\.settings\\.yml"
message: "Ensure strong password policies are configured to require complexity, length, and prevent common passwords."
-
+
# Pattern 2: Custom authentication without proper validation
- pattern: "(authenticate|login|auth).*function[^}]*return\\s+(TRUE|true|1)\\s*;"
message: "Custom authentication functions should implement proper validation and not return TRUE without checks."
-
+
# Pattern 3: Improper password comparison
- pattern: "==\\s*\\$password|===\\s*\\$password|strcmp\\(|password_verify\\([^,]+,[^,]+\\$plainTextPassword"
message: "Avoid direct password comparison. Use Drupal's built-in password verification services."
-
+
# Pattern 4: Credentials in code
- pattern: "(username|user|pass|password|pwd)\\s*=\\s*['\"][^'\"]+['\"]"
message: "Hardcoded credentials detected. Store credentials securely outside of code."
-
+
# Pattern 5: Missing or weak CSRF protection
- pattern: "drupal_get_token\\(|form_token|\\$form\\[['\"]#token['\"]\\]\\s*=|drupal_valid_token\\("
message: "Ensure proper CSRF protection is implemented for all authenticated actions."
-
+
# Pattern 6: Insecure session management
- pattern: "setcookie\\(|session_regenerate_id\\(false\\)|session_regenerate_id\\([^\\)]*"
message: "Use Drupal's session management. If custom code is required, ensure secure session handling practices."
-
+
# Pattern 7: Missing account lockout protection
- pattern: "user\\.flood\\.yml|flood_control|UserFloodControl|user_failed_login_"
message: "Ensure proper account lockout and flood control mechanisms are configured to prevent brute force attacks."
-
+
# Pattern 8: Insecure password reset implementation
- pattern: "user_pass_reset|password_reset|reset.*token"
message: "Verify password reset functionality uses secure tokens with proper expiration and validation."
-
+
# Pattern 9: Lack of multi-factor authentication
- pattern: "tfa|two_factor|multi_factor|2fa"
message: "Consider implementing multi-factor authentication for sensitive operations or user roles."
-
+
# Pattern 10: Default or test accounts
- pattern: "\\$user->name\\s*=\\s*['\"]admin['\"]|\\$name\\s*=\\s*['\"]admin['\"]|->values\\(['\"](mdc:name|mail)['\"]\\)\\s*->\\s*set\\(['\"][^\\'\"]+['\"]\\)"
message: "Avoid creating default administrator accounts or test users in production code."
@@ -62,35 +62,35 @@ actions:
- type: suggest
message: |
**Drupal Authentication Security Best Practices:**
-
+
1. **Password Policies:**
- Use Drupal's Password Policy module for enforcing strong passwords
- Configure minimum password length (12+ characters recommended)
- Require complexity (uppercase, lowercase, numbers, special characters)
- Implement password rotation for sensitive roles
- Check passwords against known breached password databases
-
+
2. **Authentication Infrastructure:**
- Use Drupal's core authentication mechanisms rather than custom solutions
- Implement proper account lockout after failed login attempts
- Consider multi-factor authentication (TFA module) for privileged accounts
- Implement session timeout for inactivity
- Use HTTPS for all authentication traffic
-
+
3. **Session Management:**
- Use Drupal's session management system rather than PHP's session functions
- Configure secure session cookie settings in settings.php
- Implement proper session regeneration on privilege changes
- Consider using the Session Limit module to restrict concurrent sessions
- Properly destroy sessions on logout
-
+
4. **Account Management:**
- Implement proper account provisioning and deprovisioning processes
- Use email verification for new account registration
- Implement secure password reset mechanisms with limited-time tokens
- Apply the principle of least privilege for user roles
- Regularly audit user accounts and permissions
-
+
5. **Authentication Hardening:**
- Monitor for authentication failures and suspicious patterns
- Implement IP-based and username-based flood control
@@ -103,15 +103,15 @@ actions:
# Check 1: Proper password handling
- pattern: "password_verify\\(|UserPassword|\\\\Drupal::service\\(['\"]password['\"]\\)"
message: "Using Drupal's password services correctly."
-
+
# Check 2: CSRF token implementation
- pattern: "\\$form\\[['\"]#token['\"]\\]\\s*=\\s*['\"][^'\"]+['\"]"
message: "Form includes CSRF protection token."
-
+
# Check 3: Proper session management
- pattern: "\\$request->getSession\\(\\)|\\\\Drupal::service\\(['\"]session['\"]\\)"
message: "Using Drupal's session management services."
-
+
# Check 4: User flood control
- pattern: "user\\.flood\\.yml|flood|user_login_final_validate"
message: "Implementing user flood protection."
@@ -136,4 +136,6 @@ metadata:
- "https://www.drupal.org/docs/security-in-drupal/drupal-security-best-practices"
- "https://www.drupal.org/project/tfa"
- "https://www.drupal.org/project/password_policy"
-
\ No newline at end of file
+```
+
+
diff --git a/.cursor/rules/drupal-broken-access-control.mdc b/.cursor/rules/drupal-broken-access-control.mdc
index 4166475..fa98f23 100644
--- a/.cursor/rules/drupal-broken-access-control.mdc
+++ b/.cursor/rules/drupal-broken-access-control.mdc
@@ -7,7 +7,7 @@ alwaysApply: false
This rule enforces security best practices to prevent broken access control vulnerabilities in Drupal applications, as defined in OWASP Top 10:2021-A01.
-
+```yaml
name: drupal_broken_access_control
description: Detect and prevent broken access control vulnerabilities in Drupal as defined in OWASP Top 10:2021-A01
filters:
@@ -22,39 +22,39 @@ actions:
# Pattern 1: Missing access checks in routes
- pattern: "\\s*\\$routes\\['[^']*'\\]\\s*=\\s*.*(?!_access|access_callback|requirements)"
message: "Route definition is missing access control. Add '_permission', '_role', '_access', or custom access check in requirements."
-
+
# Pattern 2: Using user_access() instead of more secure methods
- pattern: "user_access\\("
message: "user_access() is deprecated. Use $account->hasPermission() or proper dependency injection with AccessResult methods."
-
+
# Pattern 3: Hard-coded user ID checks
- pattern: "(\\$user->id\\(\\)|\\$user->uid)\\s*===?\\s*1"
message: "Avoid hardcoded checks against user ID 1. Use role-based permissions or proper access control services."
-
+
# Pattern 4: Missing access check on entity operations
- pattern: "\\$entity->(?!access)(save|delete|update)\\(\\)"
message: "Entity operation without prior access check. Use \$entity->access('operation') before performing operations."
-
+
# Pattern 5: Using Drupal::currentUser() directly in services
- pattern: "\\\\Drupal::currentUser\\(\\)"
message: "Avoid using \\Drupal::currentUser() directly. Inject the current_user service for better testability and security."
-
+
# Pattern 6: Missing access checks in controllers
- pattern: "class [A-Za-z0-9_]+Controller.+extends ControllerBase[^}]+public function [a-zA-Z0-9_]+\\([^{]*\\)\\s*\\{(?![^}]*access)"
message: "Controller method lacks explicit access checking. Add checks via route requirements or within the controller method."
-
+
# Pattern 7: Direct field value manipulation without access check
- pattern: "\\$entity->set\\([^)]+\\)\\s*;(?![^;]*access)"
message: "Direct field value manipulation without access check. Verify entity field access before manipulation."
-
+
# Pattern 8: Unprotected REST endpoints
- pattern: "@RestResource\\([^)]*\\)(?![^{]*_access|access_callback)"
message: "REST resource lacks access controls. Add access checks via annotations or in methods."
-
+
# Pattern 9: Insecure access check by client IP
- pattern: "\\$_SERVER\\['REMOTE_ADDR'\\]\\s*===?\\s*"
message: "IP-based access control is insufficient. Use proper Drupal permission system instead."
-
+
# Pattern 10: Allow bypassing cache for authenticated users without proper checks
- pattern: "#cache\\['contexts'\\]\\s*=\\s*\\[[^\\]]*'user'[^\\]]*\\]"
message: "Using 'user' cache context without proper access checks may expose content to unauthorized users."
@@ -62,27 +62,27 @@ actions:
- type: suggest
message: |
**Drupal Access Control Best Practices:**
-
+
1. **Route Access Controls:**
- Always define access requirements in route definitions
- Use permission-based access checks: '_permission', '_role', '_entity_access'
- Implement custom access checkers implementing AccessInterface
-
+
2. **Entity Access Controls:**
- - Always check entity access: $entity->access('view'|'update'|'delete')
+ - Always check entity access: $entity->access('view'|'update'|'delete')
- Use EntityAccessControlHandler for consistent access control
- Respect entity field access with $entity->get('field')->access('view'|'edit')
-
+
3. **Controller Security:**
- Inject and use proper services rather than \Drupal static calls
- Add explicit access checks within controller methods
- Use AccessResult methods (allowed, forbidden, neutral) with proper caching metadata
-
+
4. **Service Security:**
- Inject AccountProxyInterface rather than calling currentUser() directly
- Use dependency injection for access-related services
- Implement session-based CSRF protection with form tokens
-
+
5. **REST/API Security:**
- Implement OAuth or proper authentication
- Define specific permissions for REST operations
@@ -93,15 +93,15 @@ actions:
# Check 1: Ensuring proper access check implementation
- pattern: "AccessResult::(allowed|forbidden|neutral)\\(\\)(?=.*addCacheContexts)"
message: "Access check is properly implemented with cache metadata."
-
+
# Check 2: Proper hook_entity_access implementation
- pattern: "function hook_entity_access\\([^)]*\\)\\s*\\{[^}]*return AccessResult"
message: "Entity access hook is correctly returning AccessResult."
-
+
# Check 3: Properly secured route access
- pattern: "_permission|_role|_access|_entity_access|_custom_access"
message: "Route has proper access controls defined."
-
+
# Check 4: Secure REST implementation
- pattern: "@RestResource\\(.*,\\s*authentication\\s*=\\s*\\{[^}]+\\}"
message: "REST Resource has authentication configured."
@@ -125,4 +125,5 @@ metadata:
- "https://owasp.org/Top10/A01_2021-Broken_Access_Control/"
- "https://www.drupal.org/docs/8/api/routing-system/access-checking-on-routes"
- "https://www.drupal.org/docs/8/api/entity-api/entity-access-api"
-
\ No newline at end of file
+```
+
diff --git a/.cursor/rules/drupal-cryptographic-failures.mdc b/.cursor/rules/drupal-cryptographic-failures.mdc
index a116255..6ffdd45 100644
--- a/.cursor/rules/drupal-cryptographic-failures.mdc
+++ b/.cursor/rules/drupal-cryptographic-failures.mdc
@@ -7,7 +7,7 @@ alwaysApply: false
This rule enforces security best practices to prevent cryptographic failures in Drupal applications, as defined in OWASP Top 10:2021-A02.
-
+```yaml
name: drupal_cryptographic_failures
description: Detect and prevent cryptographic failures in Drupal as defined in OWASP Top 10:2021-A02
filters:
@@ -22,39 +22,39 @@ actions:
# Pattern 1: Use of weak hash algorithms
- pattern: "(md5|sha1)\\([^)]*\\)"
message: "Weak hash algorithm detected. Use password_hash() for passwords or hash('sha256'/'sha512') for other data."
-
+
# Pattern 2: Hardcoded credentials or keys
- pattern: "(password|key|token|secret|credentials|pwd)\\s*=\\s*['\"][^'\"]+['\"]"
message: "Hardcoded credentials or sensitive keys detected. Use Drupal's State API, key module, or environment variables."
-
+
# Pattern 3: Plaintext password storage
- pattern: "\\$user->setPassword\\((?!password_hash|\\$hash)[^)]+\\)"
message: "Never store plaintext passwords. Drupal handles password hashing internally."
-
+
# Pattern 4: Improper file encryption
- pattern: "file_(get|put)_contents\\([^,]+,\\s*[^,]+\\)"
message: "Consider encrypting sensitive file contents using Drupal's encryption API or PHP's openssl functions."
-
+
# Pattern 5: Unprotected sensitive data in settings
- pattern: "\\$settings\\[['\"](mdc:?!hash_salt|update_free_access)[^]]+\\]\\s*=\\s*['\"][^\"']+['\"]"
message: "Sensitive data in settings.php should be moved to environment variables or settings.local.php."
-
+
# Pattern 6: Insecure random number generation
- pattern: "(rand|mt_rand|array_rand)\\("
message: "Insecure random number generation. Use random_bytes() or random_int() for cryptographic purposes."
-
+
# Pattern 7: Missing HTTPS enforcement
- pattern: "'#cache'|'cache'"
message: "Ensure HTTPS is enforced for cached pages containing sensitive information."
-
+
# Pattern 8: Missing encryption for content with private information
- pattern: "(->set|->get)\\('field_[^']*(?:password|ssn|credit|card|secret|key|token|credentials|pwd)[^']*'\\)"
message: "Consider using field encryption for sensitive data fields."
-
+
# Pattern 9: Custom session handling without proper security
- pattern: "session_(start|regenerate_id)"
message: "Avoid custom session handling. Use Drupal's session management services."
-
+
# Pattern 10: API tokens without expiration or rotation
- pattern: "\\$token\\s*=\\s*.*?\\$[^;]+;(?![^;]*expir|[^;]*valid)"
message: "API tokens should include expiration time or rotation mechanism."
@@ -62,35 +62,35 @@ actions:
- type: suggest
message: |
**Drupal Cryptographic Security Best Practices:**
-
+
1. **Secure Data Storage:**
- Use Drupal's Key module for storing encryption keys
- Store sensitive configuration in environment variables or settings.local.php
- Use Drupal's State API for non-configuration sensitive data
- Never store plaintext sensitive information in the database
-
+
2. **Encryption and Hashing:**
- Use Drupal's password hashing system, which uses password_hash() internally
- For non-password data hashing, use SHA-256 or SHA-512
- Use the Encrypt module or PHP's openssl_encrypt() with proper algorithms (AES-256-GCM)
- Always use proper salting techniques
-
+
3. **Communication Security:**
- Enforce HTTPS site-wide using settings.php configuration
- Use secure cookies (secure, HttpOnly, SameSite)
- Implement proper Content-Security-Policy headers
- Use TLS 1.2+ for all connections
-
+
4. **API Security:**
- Use OAuth or JWT with proper signature verification
- Implement token expiration and rotation
- Use HMAC for API request signatures when appropriate
- Never expose internal encryption keys through APIs
-
+
5. **Configuration Best Practices:**
- Regularly rotate encryption keys and credentials
- Implement secure key storage using key management services
- - Monitor and log cryptographic operations
+ - Monitor and log cryptographic operations
- Maintain an inventory of cryptographic algorithms in use
- type: validate
@@ -98,15 +98,15 @@ actions:
# Check 1: Proper password handling
- pattern: "UserInterface::PASSWORD_|password_hash\\("
message: "Using Drupal's password system correctly."
-
+
# Check 2: Proper random generation
- pattern: "random_bytes|random_int|\\\\Drupal::service\\('random'\\)"
message: "Using secure random generation methods."
-
+
# Check 3: Secure settings
- pattern: "getenv\\('|\\$_ENV\\['|\\$_SERVER\\['|settings\\.local\\.php"
message: "Using environment variables or local settings correctly."
-
+
# Check 4: Proper encryption usage
- pattern: "openssl_encrypt\\(|\\\\Drupal::service\\('encryption'\\)"
message: "Using proper encryption methods."
@@ -131,4 +131,6 @@ metadata:
- "https://www.drupal.org/docs/security-in-drupal"
- "https://www.drupal.org/project/key"
- "https://www.drupal.org/project/encrypt"
-
\ No newline at end of file
+```
+
+
diff --git a/.cursor/rules/drupal-database-standards.mdc b/.cursor/rules/drupal-database-standards.mdc
index d325295..a3dc8ba 100644
--- a/.cursor/rules/drupal-database-standards.mdc
+++ b/.cursor/rules/drupal-database-standards.mdc
@@ -6,7 +6,7 @@ globs: *.php, *.install, *.module
Ensures proper database handling in Drupal applications.
-
+```yaml
name: drupal_database_standards
description: Enforce Drupal database best practices and standards
filters:
@@ -37,4 +37,6 @@ actions:
metadata:
priority: critical
version: 1.0
-
\ No newline at end of file
+```
+
+
diff --git a/.cursor/rules/drupal-file-permissions.mdc b/.cursor/rules/drupal-file-permissions.mdc
index ac45a4b..5817632 100644
--- a/.cursor/rules/drupal-file-permissions.mdc
+++ b/.cursor/rules/drupal-file-permissions.mdc
@@ -6,7 +6,7 @@ globs: *.dockerfile, *.sh, docker-compose.yml, Dockerfile
Standards for securing Drupal file permissions in Docker environments and production servers, ensuring proper security while maintaining functionality.
-
+```yaml
name: drupal_file_permissions
description: Enforce secure file permissions for Drupal sites/default directory and critical files
filters:
@@ -28,10 +28,10 @@ actions:
- pattern: "chmod\\s+(?!444)\\d+\\s+[^\\n]*services\\.yml"
message: "services.yml should have 444 permissions (read-only for everyone)"
-
+
- pattern: "chmod\\s+(?!755)\\d+\\s+[^\\n]*sites\\/default\\/files"
message: "sites/default/files directory should have 755 permissions with proper ownership"
-
+
- pattern: "chown\\s+(?!www-data:www-data)[^\\s]+\\s+[^\\n]*sites\\/default\\/files"
message: "sites/default/files should be owned by the web server user (www-data:www-data)"
@@ -50,7 +50,7 @@ actions:
### 2. Ownership Configuration
- **Web root**: application user (varies by environment)
- **sites/default/files**: web server user (www-data:www-data)
-
+
### 3. Implementation in Dockerfile
```dockerfile
# Set proper permissions for Drupal
@@ -67,31 +67,31 @@ actions:
Create a script at `/app/scripts/custom/fix-drupal-permissions.sh`:
```bash
#!/bin/bash
-
+
# Exit on error
set -e
-
+
WEBROOT=${WEBROOT:-web}
-
+
echo "Setting Drupal file permissions..."
-
+
# Ensure directories exist
mkdir -p /app/${WEBROOT}/sites/default/files
-
+
# Set ownership
chown www-data:www-data /app/${WEBROOT}/sites/default/files
-
+
# Set directory permissions
chmod 755 /app/${WEBROOT}/sites/default
chmod 755 /app/${WEBROOT}/sites/default/files
find /app/${WEBROOT}/sites/default/files -type d -exec chmod 755 {} \;
-
+
# Set file permissions
chmod 444 /app/${WEBROOT}/sites/default/settings.php
[ -f /app/${WEBROOT}/sites/default/services.yml ] && chmod 444 /app/${WEBROOT}/sites/default/services.yml
[ -f /app/${WEBROOT}/sites/default/settings.local.php ] && chmod 444 /app/${WEBROOT}/sites/default/settings.local.php
find /app/${WEBROOT}/sites/default/files -type f -exec chmod 644 {} \;
-
+
echo "Drupal file permissions set successfully."
```
@@ -100,7 +100,7 @@ actions:
# Check file permissions
ahoy cli "ls -la /app/${WEBROOT}/sites/default"
ahoy cli "ls -la /app/${WEBROOT}/sites/default/files"
-
+
# Check Drupal status
ahoy drush status-report | grep -i "protected"
```
@@ -131,4 +131,6 @@ examples:
metadata:
priority: high
version: 1.1
-
+```
+
+
diff --git a/.cursor/rules/drupal-injection.mdc b/.cursor/rules/drupal-injection.mdc
index 3d8a502..0fe8f61 100644
--- a/.cursor/rules/drupal-injection.mdc
+++ b/.cursor/rules/drupal-injection.mdc
@@ -7,7 +7,7 @@ alwaysApply: false
This rule enforces security best practices to prevent injection vulnerabilities in Drupal applications, as defined in OWASP Top 10:2021-A03.
-
+```yaml
name: drupal_injection
description: Detect and prevent injection vulnerabilities in Drupal as defined in OWASP Top 10:2021-A03
filters:
@@ -22,39 +22,39 @@ actions:
# Pattern 1: Raw SQL queries without placeholders
- pattern: "db_query\\(['\"][^'\"]*\\$[^'\"]*['\"]"
message: "Direct variables in SQL queries are vulnerable to SQL injection. Use parameterized queries with placeholders."
-
+
# Pattern 2: Modern DB API without placeholders
- pattern: "->query\\(['\"][^'\"]*\\$[^'\"]*['\"]"
message: "Use parameterized queries with placeholders to prevent SQL injection: ->query($sql, [$param1, $param2])."
-
+
# Pattern 3: Unescaped output
- pattern: "=|t))[^;]*;"
message: "Direct output may lead to XSS. Use t(), escaped variables with Html::escape(), or Twig templates."
-
+
# Pattern 4: Unfiltered user input in render arrays
- pattern: "[\"']#markup[\"']\\s*=>\\s*(?!t\\(|\\\\t\\(|Xss::filterAdmin|Html::escape)\\$"
message: "Never use unfiltered variables in #markup. Use t(), Xss::filterAdmin(), or Html::escape()."
-
+
# Pattern 5: Unescaped variables in JavaScript settings
- pattern: "->addJsSettings\\(\\[(?![^\\]]*(Xss::filter|Json::encode))\\$"
message: "Filter variables before adding to JavaScript settings using Xss::filter() or properly encode with Json::encode()."
-
+
# Pattern 6: Direct command execution
- pattern: "exec\\(|shell_exec\\(|system\\(|passthru\\(|proc_open\\(|popen\\(|`"
message: "Command execution functions can lead to command injection. Use Symfony\Component\Process\Process if necessary."
-
+
# Pattern 7: Unvalidated redirect
- pattern: "->redirect\\(\\s*\\$(?!(this->|allowed_destinations|config))"
message: "Unvalidated redirects can lead to open redirect vulnerabilities. Whitelist allowed destinations."
-
+
# Pattern 8: Raw user input in conditions
- pattern: "->condition\\([^,]*,\\s*\\$(?!(this->|config|entity|storage))[^,]*,"
message: "Use proper input validation before using variables in database conditions to prevent SQL injection."
-
+
# Pattern 9: Missing CSRF protection in forms
- pattern: "(?|allowed_paths|config))"
message: "Validate file paths before operations to prevent path traversal attacks."
@@ -62,31 +62,31 @@ actions:
- type: suggest
message: |
**Drupal Injection Prevention Best Practices:**
-
+
1. **SQL Injection Prevention:**
- Always use parameterized queries with placeholders
- Use the Database API's condition methods: ->condition(), ->where()
- Properly escape table and field names with {}
- Consider using EntityQuery for entity operations
-
+
2. **XSS Prevention:**
- Use Drupal's t() function for user-visible strings
- Apply appropriate filtering: Html::escape(), Xss::filter(), Xss::filterAdmin()
- Use #plain_text instead of #markup when displaying user input
- Utilize Twig's automatic escaping in templates
- For admin UIs, be careful with Xss::filterAdmin() as it allows some tags
-
+
3. **CSRF Protection:**
- Always include form tokens with $form['#token']
- Validate form tokens with FormState->validateToken()
- For AJAX requests, utilize Drupal's ajax framework
- Use drupal_valid_token() for custom validation
-
+
4. **Command Injection Prevention:**
- Avoid command execution functions entirely
- Use Symfony\Component\Process\Process with escaped arguments
- Validate and whitelist any input used in command contexts
-
+
5. **Path Traversal Prevention:**
- Validate file paths with FileSystem::validatedLocalFileSystem()
- Use stream wrappers (public://, private://) instead of direct paths
@@ -97,15 +97,15 @@ actions:
# Check 1: Proper SQL query usage
- pattern: "->query\\(['\"][^'\"]*\\?[^'\"]*['\"],\\s*\\[[^\\]]*\\]\\)"
message: "Properly using parameterized queries with placeholders."
-
+
# Check 2: Proper XSS prevention
- pattern: "(t\\(|Xss::filter|Html::escape|#plain_text)"
message: "Using proper XSS prevention techniques."
-
+
# Check 3: Proper CSRF protection
- pattern: "#token|FormBuilderInterface::TOKEN|drupal_valid_token"
message: "Implementing CSRF protection correctly."
-
+
# Check 4: Safe file operations
- pattern: "FileSystem::validatedLocalFileSystem|file_exists\\(\\s*DRUPAL_ROOT"
message: "Using safe file operation practices."
@@ -132,4 +132,6 @@ metadata:
- "https://www.drupal.org/docs/security-in-drupal/writing-secure-code-for-drupal"
- "https://www.drupal.org/docs/8/security/drupal-8-sanitizing-output"
- "https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Component%21Utility%21Xss.php/class/Xss/9"
-
\ No newline at end of file
+```
+
+
diff --git a/.cursor/rules/drupal-insecure-design.mdc b/.cursor/rules/drupal-insecure-design.mdc
index 1402dc6..76ae6a7 100644
--- a/.cursor/rules/drupal-insecure-design.mdc
+++ b/.cursor/rules/drupal-insecure-design.mdc
@@ -7,7 +7,7 @@ alwaysApply: false
This rule enforces security best practices to prevent insecure design vulnerabilities in Drupal applications, as defined in OWASP Top 10:2021-A04.
-
+```yaml
name: drupal_insecure_design
description: Detect and prevent insecure design patterns in Drupal as defined in OWASP Top 10:2021-A04
filters:
@@ -22,39 +22,39 @@ actions:
# Pattern 1: Insecure permission design
- pattern: "\\$permissions\\[['\"][^'\"]+['\"]\\]\\s*=\\s*array\\((?![^)]*(administer|manage|edit|delete)[^)]*(content|configuration|users)).*?\\);"
message: "Permissions should follow Drupal naming patterns (verb + object) and be specific. Avoid overly broad permissions."
-
+
# Pattern 2: Hard-coded business logic values
- pattern: "if\\s*\\([^\\)]*===?\\s*['\"][a-zA-Z0-9_]+['\"]\\s*\\)"
message: "Consider moving business logic rules to configuration to allow for proper adjustment without code changes."
-
+
# Pattern 3: Ad hoc input sanitization
- pattern: "preg_replace|str_replace|strip_tags"
message: "Avoid ad hoc sanitization. Use Drupal's built-in sanitization tools: t(), Xss::filter(), etc."
-
+
# Pattern 4: Database logic in controllers
- pattern: "class\\s+[a-zA-Z0-9_]+Controller.+\\{[^}]*->query\\("
message: "Follow separation of concerns. Move database logic to services or repositories, not in controllers."
-
+
# Pattern 5: Weak entity access policy
- pattern: "function\\s+[a-zA-Z0-9_]+_entity_access\\([^)]*\\)\\s*\\{[^}]*return\\s+AccessResult::allowed\\(\\);"
message: "Avoid unconditional access grants. Implement proper conditional checks based on roles, permissions, or entity ownership."
-
- # Pattern 6: Custom session management
+
+ # Pattern 6: Custom session management
- pattern: "session_start|session_set_cookie_params"
message: "Avoid custom session management. Use Drupal's session handling system and services."
-
+
# Pattern 7: Excessive global state dependency
- pattern: "(?:\\\\Drupal::[a-zA-Z_]+\\(\\).*){3,}"
message: "Excessive static service calls indicate poor dependency injection. Use proper service injection."
-
+
# Pattern 8: Custom user authentication
- pattern: "password_verify\\(|password_hash\\("
message: "Avoid custom authentication. Use Drupal's built-in authentication system and services."
-
+
# Pattern 9: Missing schema definitions
- pattern: "function\\s+[a-zA-Z0-9_]+_schema\\(\\)[^{]*\\{[^}]*return\\s+\\$schema;(?![^}]*validate_utf8|[^}]*'not null')"
message: "Database schemas should enforce data integrity with proper constraints (NOT NULL, length, etc.)."
-
+
# Pattern 10: Insecure defaults
- pattern: "\\$config\\[['\"](mdc:?!secure_|security_|private_)[^'\"]+['\"]\\]\\s*=\\s*(?:FALSE|0|'0'|\"0\");"
message: "Security-related configuration should default to secure settings (opt-in for potentially insecure features)."
@@ -62,35 +62,35 @@ actions:
- type: suggest
message: |
**Drupal Secure Design Best Practices:**
-
+
1. **Secure Architecture Principles:**
- Follow the principle of least privilege for all user roles and permissions
- Implement defense in depth with multiple security layers
- Use Drupal's entity/field API for structured data instead of custom tables
- Employ service-oriented architecture with proper dependency injection
- Follow Drupal coding standards to leverage community security expertise
-
+
2. **Permission System Design:**
- Design granular permissions following the verb+object pattern
- Avoid creating omnipotent permissions that grant excessive access
- Use context-aware access systems like Entity Access or Node Grants
- Consider record-based and field-based access for better control
- Document permission architecture and security implications
-
+
3. **Module Architecture:**
- Separate concerns into appropriate services
- Use hooks judiciously and document security implications
- Implement proper validation and sanitization layers
- Design APIs with security in mind from the start
- Provide secure default configurations
-
+
4. **Data Modeling Security:**
- Implement appropriate validation constraints on entity fields
- Design schema definitions with integrity constraints
- Use appropriate field types for sensitive data
- Implement field-level access control when needed
- Consider encryption for sensitive stored data
-
+
5. **Error Handling and Logging:**
- Design contextual error messages (detailed for admins, general for users)
- Implement appropriate logging for security events
@@ -103,15 +103,15 @@ actions:
# Check 1: Proper dependency injection
- pattern: "protected\\s+\\$[a-zA-Z0-9_]+;[^}]*public\\s+function\\s+__construct\\([^\\)]*\\)"
message: "Using proper dependency injection pattern."
-
+
# Check 2: Configuration schema usage
- pattern: "config\\/schema\\/[a-zA-Z0-9_]+\\.schema\\.yml"
message: "Providing configuration schema for validation."
-
+
# Check 3: Proper permission definition
- pattern: "\\$permissions\\[['\"][a-z\\s]+[a-z0-9\\s]+['\"]\\]\\s*=\\s*\\["
message: "Following permission naming conventions."
-
+
# Check 4: Entity access handlers
- pattern: "@EntityAccessControl\\(|class\\s+[a-zA-Z0-9_]+AccessControlHandler\\s+extends\\s+"
message: "Using dedicated access control handlers for entities."
@@ -136,4 +136,6 @@ metadata:
- "https://www.drupal.org/docs/develop/security-in-drupal"
- "https://www.drupal.org/docs/8/api/entity-api/access-control-for-entities"
- "https://www.drupal.org/docs/8/api/configuration-api/configuration-schemametadata"
-
\ No newline at end of file
+```
+
+
diff --git a/.cursor/rules/drupal-integrity-failures.mdc b/.cursor/rules/drupal-integrity-failures.mdc
index 2af8004..80802d2 100644
--- a/.cursor/rules/drupal-integrity-failures.mdc
+++ b/.cursor/rules/drupal-integrity-failures.mdc
@@ -7,7 +7,7 @@ alwaysApply: false
This rule enforces security best practices to prevent software and data integrity failures in Drupal applications, as defined in OWASP Top 10:2021-A08.
-
+```yaml
name: drupal_integrity_failures
description: Detect and prevent software and data integrity failures in Drupal as defined in OWASP Top 10:2021-A08
filters:
@@ -22,39 +22,39 @@ actions:
# Pattern 1: Insecure deserialization
- pattern: "unserialize\\(\\$|unserialize\\([^,]+\\$|php_unserialize\\(\\$"
message: "Insecure PHP deserialization detected. Use safer alternatives like JSON for data interchange or implement proper validation before deserialization."
-
+
# Pattern 2: Unsafe use of eval or similar functions
- pattern: "eval\\(|assert\\(|create_function\\("
message: "Potentially dangerous code execution function detected. Avoid dynamic code execution whenever possible."
-
+
# Pattern 3: Insecure plugin/module loading
- pattern: "module_load_include\\(\\$|require(_once)?\\s*\\(\\s*\\$|include(_once)?\\s*\\(\\s*\\$"
message: "Dynamic inclusion of files based on user input is dangerous. Use validated, allowlisted paths only."
-
+
# Pattern 4: Missing update verification
- pattern: "update\\.settings\\.yml|function [a-zA-Z0-9_]+_update_[0-9]+\\(\\)"
message: "Ensure update hooks validate the integrity of updates and data transformations to prevent unauthorized modifications."
-
+
# Pattern 5: Unsafe configuration imports
- pattern: "ConfigImporter|\\$config_importer|config_import|cmci"
message: "Validate configuration before import to ensure integrity and detect potentially malicious changes."
-
+
# Pattern 6: Unchecked remote data
- pattern: "drupal_http_request\\(|\\\\Drupal::httpClient\\(\\)->get\\(|curl_exec\\("
message: "Always validate data from remote sources before processing or storing it. Implement integrity checks for remote content."
-
+
# Pattern 7: Insecure Composer usage
- pattern: "composer\\.json"
message: "Verify you're using secure Composer practices: validate package signatures, pin dependencies, and use composer.lock."
-
+
# Pattern 8: Direct database modifications
- pattern: "INSERT\\s+INTO|UPDATE\\s+[a-zA-Z0-9_]+\\s+SET|db_update\\(|->update\\(|->insert\\("
message: "Direct database modifications should implement validation to preserve data integrity. Prefer using entity API."
-
+
# Pattern 9: Missing file integrity verification
- pattern: "file_save_data\\(|file_save_upload\\(|file_copy\\(|file_move\\("
message: "Implement file integrity checking for uploaded or manipulated files to prevent malicious content."
-
+
# Pattern 10: Unsafe entity creation
- pattern: "\\$entity\\s*=\\s*new\\s+[A-Za-z]+\\(|::create\\(\\$"
message: "Validate all input used to create entity objects to maintain data integrity and prevent creating malicious entities."
@@ -62,35 +62,35 @@ actions:
- type: suggest
message: |
**Drupal Data & Software Integrity Best Practices:**
-
+
1. **Secure Deserialization:**
- Avoid PHP's unserialize() with untrusted data entirely
- Use JSON or other structured formats for data interchange
- When deserialization is necessary, implement allowlists and validation
- Consider using Drupal's typed data API for structured data handling
- Avoid serializing sensitive data that could be tampered with
-
+
2. **Update & Configuration Integrity:**
- Validate data before and after migrations/updates
- Implement checksums/hashing for critical configuration
- Use Drupal's Configuration Management system properly
- Monitor configuration changes for unauthorized modifications
- Implement proper workflow for configuration management
-
+
3. **Dependency & Plugin Security:**
- Verify the integrity of downloaded modules and themes
- Use Composer with package signature verification
- Pin dependencies to specific versions in production
- Maintain awareness of security advisories
- Implement proper validation for plugin/module loading
-
+
4. **CI/CD Pipeline Security:**
- Sign build artifacts
- Verify signatures during deployment
- Implement proper secrets management
- Control access to build and deployment systems
- Validate code changes through code reviews
-
+
5. **Data Integrity Validation:**
- Use database constraints to enforce data integrity
- Implement validation at every layer of the application
@@ -103,15 +103,15 @@ actions:
# Check 1: Secure serialization alternatives
- pattern: "json_encode|json_decode|\\\\Drupal::service\\('serialization\\.|->toArray\\(\\)"
message: "Using safer serialization alternatives."
-
+
# Check 2: Proper entity validation
- pattern: "\\$entity->validate\\(\\)|\\$violations\\s*=\\s*\\$entity->validate\\(\\)"
message: "Properly validating entity data."
-
+
# Check 3: Config verification
- pattern: "::validateSyncedConfig\\(|ConfigImporter::validate|->getUnprocessedConfiguration\\(\\)"
message: "Implementing configuration validation."
-
+
# Check 4: Safe file handling
- pattern: "file_validate_|FileValidatorInterface|\\$validators"
message: "Using file validation mechanisms."
@@ -136,4 +136,6 @@ metadata:
- "https://www.drupal.org/docs/develop/security-in-drupal/drupal-8-sanitizing-output"
- "https://www.drupal.org/docs/8/api/configuration-api/configuration-api-overview"
- "https://www.drupal.org/docs/develop/using-composer"
-
\ No newline at end of file
+```
+
+
diff --git a/.cursor/rules/drupal-logging-failures.mdc b/.cursor/rules/drupal-logging-failures.mdc
index 6ce9692..95e7142 100644
--- a/.cursor/rules/drupal-logging-failures.mdc
+++ b/.cursor/rules/drupal-logging-failures.mdc
@@ -7,7 +7,7 @@ alwaysApply: false
This rule enforces security best practices to prevent logging and monitoring failures in Drupal applications, as defined in OWASP Top 10:2021-A09.
-
+```yaml
name: drupal_logging_failures
description: Detect and prevent security logging and monitoring failures in Drupal as defined in OWASP Top 10:2021-A09
filters:
@@ -22,39 +22,39 @@ actions:
# Pattern 1: Missing critical event logging
- pattern: "(delete|update|create|execute|grant|revoke|config|schema).*function[^}]*\\{(?![^}]*(log|watchdog|logger))"
message: "Critical operations should include logging. Implement proper logging for security-relevant actions."
-
+
# Pattern 2: Suppressed error logging
- pattern: "@include|@require|@eval|error_reporting\\(0\\)|ini_set\\(['\"](mdc:display_errors|log_errors)['\"],\\s*['\"]0['\"]\\)"
message: "Avoid suppressing errors and warnings. Implement proper error handling and logging instead."
-
+
# Pattern 3: Improper exception handling without logging
- pattern: "catch\\s*\\([^{]*\\)\\s*\\{(?![^}]*log|[^}]*watchdog|[^}]*logger)"
message: "Exceptions should be properly logged, especially in security-critical sections."
-
+
# Pattern 4: Disabled watchdog
- pattern: "dblog\\.settings\\.yml|syslog\\.settings\\.yml|logging\\.settings\\.yml"
message: "Ensure logging is properly configured and not disabled. Verify log verbosity and retention policies."
-
+
# Pattern 5: Missing authentication event logging
- pattern: "(login|authenticate|logout|password).*function[^}]*\\{(?![^}]*(log|watchdog|logger))"
message: "Authentication events should always be logged for security monitoring and auditing."
-
+
# Pattern 6: Failure to log access control decisions
- pattern: "AccessResult::(allowed|forbidden|neutral)\\([^)]*\\)(?![^;]*(log|watchdog|logger))"
message: "Consider logging significant access control decisions, especially denials, for security monitoring."
-
+
# Pattern 7: Missing logging in file operations
- pattern: "(file_save|file_delete|file_move|file_copy)[^;]*;(?![^;]*(log|watchdog|logger))"
message: "File operations should be logged, especially for security-sensitive files."
-
+
# Pattern 8: Insufficient detail in log messages
- pattern: "(\\->log|watchdog)\\([^,)]*,[^,)]*\\)"
message: "Log messages should include sufficient context and detail for effective security monitoring."
-
+
# Pattern 9: Failure to log configuration changes
- pattern: "\\$config->set\\([^;]*;(?![^;]*(log|watchdog|logger))"
message: "Configuration changes should be logged to maintain an audit trail and detect unauthorized changes."
-
+
# Pattern 10: Missing logs for API access
- pattern: "class\\s+[a-zA-Z0-9_]+Resource.+\\{[^}]*function\\s+[a-zA-Z0-9_]+\\([^{]*\\)\\s*\\{(?![^}]*(log|watchdog|logger))"
message: "API endpoint access should be logged for security monitoring, especially for sensitive operations."
@@ -62,14 +62,14 @@ actions:
- type: suggest
message: |
**Drupal Security Logging & Monitoring Best Practices:**
-
+
1. **Comprehensive Logging Implementation:**
- Use Drupal's Logger Factory service: `\Drupal::logger('module_name')`
- Implement proper log levels: emergency, alert, critical, error, warning, notice, info, debug
- Include context in log messages with relevant identifiers and information
- Log security-relevant events consistently across the application
- Structure log messages to facilitate automated analysis
-
+
2. **Critical Events to Log:**
- Authentication events (login attempts, failures, logouts)
- Access control decisions (particularly denials)
@@ -78,21 +78,21 @@ actions:
- Configuration and settings changes
- File operations (uploads, downloads of sensitive content)
- API access and usage
-
+
3. **Logging Configuration:**
- Configure appropriate log retention periods based on security requirements
- Implement log rotation to maintain performance
- Consider using syslog for centralized logging
- Protect log files from unauthorized access and modification
- Configure appropriate verbosity for different environments
-
+
4. **Monitoring Implementation:**
- Define security-relevant log patterns to monitor
- Implement log aggregation and analysis
- Set up alerts for suspicious activity patterns
- Establish response procedures for security events
- Consider integration with SIEM solutions
-
+
5. **Error Handling:**
- Log exceptions with appropriate error levels
- Include stack traces in development but not production
@@ -105,15 +105,15 @@ actions:
# Check 1: Proper logger usage
- pattern: "\\\\Drupal::logger\\([^)]+\\)->\\w+\\(|\\$this->logger->\\w+\\("
message: "Using Drupal's logger service correctly."
-
+
# Check 2: Context in log messages
- pattern: "->\\w+\\([^,]+,\\s*[^,]+,\\s*\\["
message: "Including context information in log messages."
-
+
# Check 3: Logging configuration
- pattern: "dblog\\.settings|syslog\\.settings|logging\\.yml"
message: "Configuring logging appropriately."
-
+
# Check 4: Exception logging
- pattern: "catch[^{]*\\{[^}]*logger|catch[^{]*\\{[^}]*watchdog|catch[^{]*\\{[^}]*log"
message: "Properly logging exceptions."
@@ -138,4 +138,6 @@ metadata:
- "https://www.drupal.org/docs/8/api/logging-api/overview"
- "https://www.drupal.org/docs/develop/security-in-drupal/writing-secure-code-for-drupal"
- "https://www.drupal.org/docs/8/modules/syslog"
-
\ No newline at end of file
+```
+
+
diff --git a/.cursor/rules/drupal-security-misconfiguration.mdc b/.cursor/rules/drupal-security-misconfiguration.mdc
index a51b6e8..4da66a9 100644
--- a/.cursor/rules/drupal-security-misconfiguration.mdc
+++ b/.cursor/rules/drupal-security-misconfiguration.mdc
@@ -7,7 +7,7 @@ alwaysApply: false
This rule enforces security best practices to prevent misconfiguration vulnerabilities in Drupal applications, as defined in OWASP Top 10:2021-A05.
-
+```yaml
name: drupal_security_misconfiguration
description: Detect and prevent security misconfigurations in Drupal as defined in OWASP Top 10:2021-A05
filters:
@@ -22,39 +22,39 @@ actions:
# Pattern 1: Development settings in production code
- pattern: "\\$settings\\['update_free_access'\\]\\s*=\\s*TRUE|\\$settings\\['cache'\\]\\s*=\\s*FALSE|\\$settings\\['rebuild_access'\\]\\s*=\\s*TRUE|\\$config\\['system\\.performance'\\]\\['cache'\\]\\s*=\\s*FALSE"
message: "Development settings detected in production code. Ensure these settings are only enabled in development environments."
-
+
# Pattern 2: Missing or weak trusted host patterns
- pattern: "settings\\.php|settings\\.local\\.php"
message: "Verify that $settings['trusted_host_patterns'] is properly configured to prevent HTTP Host header attacks."
-
+
# Pattern 3: Debugging/error display enabled
- pattern: "\\$config\\['system\\.logging'\\]\\['error_level'\\]\\s*=\\s*'verbose'|ini_set\\('display_errors'\\s*,\\s*'1'\\)|error_reporting\\(E_ALL\\)"
message: "Error display should be disabled in production. Use 'hide' for error_level in production."
-
+
# Pattern 4: Insecure file permissions settings
- pattern: "\\$settings\\['file_chmod_directory'\\]\\s*=\\s*0777|\\$settings\\['file_chmod_file'\\]\\s*=\\s*0666"
message: "Excessively permissive file permissions detected. Use more restrictive permissions."
-
+
# Pattern 5: Disabled or misconfigured CSP headers
- pattern: "\\.htaccess|sites/default/default\\.settings\\.php"
message: "Ensure Content-Security-Policy headers are properly configured to prevent XSS attacks."
-
+
# Pattern 6: Insecure session cookie settings
- pattern: "session\\.cookie_secure\\s*=\\s*0|session\\.cookie_httponly\\s*=\\s*0|\\$settings\\['cookie_secure_only'\\]\\s*=\\s*FALSE"
message: "Session cookies should be secure and HTTP-only in production environments."
-
+
# Pattern 7: Missing or misconfigured private file path
- pattern: "settings\\.php"
message: "Ensure $settings['file_private_path'] is properly configured for storing sensitive files."
-
+
# Pattern 8: Development modules enabled in production
- pattern: "core\\.extension\\.yml"
message: "Check for development modules (devel, webprofiler, etc.) that should not be enabled in production."
-
+
# Pattern 9: Default or demo content in production
- pattern: "function\\s+[a-zA-Z0-9_]+_install\\(\\)"
message: "Remove or secure default/demo content and users in production environments."
-
+
# Pattern 10: Missing or misconfigured security headers
- pattern: "\\.htaccess|nginx\\.conf"
message: "Verify X-Frame-Options, X-Content-Type-Options, X-XSS-Protection, and Referrer-Policy headers are properly configured."
@@ -62,31 +62,31 @@ actions:
- type: suggest
message: |
**Drupal Security Configuration Best Practices:**
-
+
1. **Environment-Specific Configurations:**
- Use `settings.local.php` for environment-specific settings
- Maintain separate development, staging, and production configurations
- Never enable development settings in production: update_free_access, rebuild_access, etc.
- Use environment variables or secrets management for sensitive information
-
+
2. **Essential Security Settings:**
- Configure trusted_host_patterns to prevent HTTP Host header attacks
- Set secure file permissions (e.g., 0755 for directories, 0644 for files)
- Configure private file path for sensitive uploads
- Set file_scan_ignore_directories to prevent public access to sensitive directories
- Implement secure session cookie settings (HTTPOnly, Secure, SameSite)
-
+
3. **Error Handling:**
- Disable verbose error reporting in production with $config['system.logging']['error_level'] = 'hide'
- Configure custom error pages that don't leak system information
- Implement appropriate logging without exposing sensitive data
-
+
4. **Security Headers:**
- Set Content-Security-Policy to restrict resource origins
- Configure X-Frame-Options to prevent clickjacking
- Enable X-Content-Type-Options to prevent MIME-type sniffing
- Set Referrer-Policy to control information in HTTP referers
-
+
5. **Module & Extension Security:**
- Disable and uninstall unnecessary modules in production
- Keep core and contributed modules updated
@@ -98,15 +98,15 @@ actions:
# Check 1: Proper trusted host patterns
- pattern: "\\$settings\\['trusted_host_patterns'\\]\\s*=\\s*\\[\\s*['\"][^\"']+['\"]"
message: "Trusted host patterns are properly configured."
-
+
# Check 2: Secure session cookie settings
- pattern: "\\$settings\\['cookie_secure_only'\\]\\s*=\\s*TRUE|session\\.cookie_secure\\s*=\\s*1"
message: "Secure cookie settings are properly configured."
-
+
# Check 3: Private file path configuration
- pattern: "\\$settings\\['file_private_path'\\]\\s*=\\s*(\"|')[^\"']+(\"|')"
message: "Private file path is configured for sensitive files."
-
+
# Check 4: Production error settings
- pattern: "\\$config\\['system\\.logging'\\]\\['error_level'\\]\\s*=\\s*'hide'"
message: "Error reporting is properly configured for production."
@@ -131,4 +131,6 @@ metadata:
- "https://www.drupal.org/docs/security-in-drupal/securing-your-site"
- "https://www.drupal.org/docs/security-in-drupal/drupal-security-best-practices"
- "https://www.drupal.org/docs/8/security/writing-secure-code-for-drupal-8"
-
\ No newline at end of file
+```
+
+
diff --git a/.cursor/rules/drupal-ssrf.mdc b/.cursor/rules/drupal-ssrf.mdc
index c48453d..be07286 100644
--- a/.cursor/rules/drupal-ssrf.mdc
+++ b/.cursor/rules/drupal-ssrf.mdc
@@ -7,7 +7,7 @@ alwaysApply: false
This rule enforces security best practices to prevent Server-Side Request Forgery (SSRF) vulnerabilities in Drupal applications, as defined in OWASP Top 10:2021-A10.
-
+```yaml
name: drupal_ssrf
description: Detect and prevent Server-Side Request Forgery (SSRF) vulnerabilities in Drupal applications as defined in OWASP Top 10:2021-A10
filters:
@@ -22,39 +22,39 @@ actions:
# Pattern 1: Unsafe URL construction with user input
- pattern: "(file_get_contents|fopen|curl_exec|drupal_http_request|\\$client->request|\\$client->get|Drupal::httpClient\\(\\)->get)\\s*\\([^)]*\\$_(GET|POST|REQUEST|COOKIE|SERVER|FILES)[^)]*\\)"
message: "Potential SSRF vulnerability: URL constructed with user input. Validate and sanitize user-supplied URL parameters before making requests."
-
+
# Pattern 2: Unsafe Guzzle HTTP client usage
- pattern: "GuzzleHttp\\\\Client[^;]*;[^;]*->request\\s*\\([^;]*\\$[^;]*"
message: "Validate and restrict URLs before making HTTP requests with Guzzle to prevent SSRF attacks."
-
+
# Pattern 3: Missing URL validation before making HTTP requests
- pattern: "(Http(Client|Request)|curl_exec|file_get_contents)\\s*\\([^)]*(http|\\$[a-zA-Z0-9_]+)[^)]*\\)[^;]*;(?![^;]*(valid|check|sanitize|UrlHelper))"
message: "HTTP requests should validate URLs with \\Drupal\\Component\\Utility\\UrlHelper::isValid() before execution to prevent SSRF."
-
+
# Pattern 4: Unsafe URL construction with variable input
- pattern: "(https?:?//|www\\.)\\s*\\.\\s*\\$[a-zA-Z0-9_]+"
message: "Potential SSRF vulnerability: URL being constructed with variable concatenation. Use URL validation and allowlisting."
-
+
# Pattern 5: Using file system wrappers which can lead to SSRF
- pattern: "file_get_contents\\([\"'](mdc:?:http|https|ftp|php|data|expect|zip|phar)://"
message: "Avoid using PHP wrappers with file operations that could lead to SSRF vulnerabilities."
-
+
# Pattern 6: Bypassing local proxy settings
- pattern: "CURLOPT_PROXY[^;]*none|CURLOPT_PROXY[^;]*null"
message: "Bypassing proxy settings can lead to SSRF vulnerabilities. Maintain proper proxy configurations."
-
+
# Pattern 7: Unsafe processing of XML with external entities
- pattern: "simplexml_load_|DOMDocument|SimpleXMLElement|xml_parse"
message: "XML processing without disabling external entities can lead to XXE and SSRF. Use libxml_disable_entity_loader(true)."
-
+
# Pattern 8: Accessing or using internal network IPs
- pattern: "(127\\.0\\.0\\.1|10\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}|172\\.(1[6-9]|2[0-9]|3[0-1])\\.[0-9]{1,3}\\.[0-9]{1,3}|192\\.168\\.[0-9]{1,3}\\.[0-9]{1,3}|169\\.254\\.[0-9]{1,3}\\.[0-9]{1,3}|localhost)"
message: "Hardcoded internal IP addresses or localhost may facilitate SSRF attacks if exposed to user manipulation."
-
+
# Pattern 9: Custom Drupal HTTP client usage without validation
- pattern: "\\\\Drupal::httpClient\\(\\)(?!.*[^;]*UrlHelper::isValid)"
message: "Always validate URLs with UrlHelper::isValid() before making HTTP requests with Drupal's HTTP client."
-
+
# Pattern 10: Allowing unrestricted ports in HTTP requests
- pattern: "curl_setopt\\([^,]+,\\s*CURLOPT_PORT,\\s*\\$[a-zA-Z0-9_]+"
message: "Potential SSRF vulnerability: Restrict allowed ports for outbound HTTP requests to prevent service probing."
@@ -62,33 +62,33 @@ actions:
- type: suggest
message: |
**Drupal SSRF Prevention Best Practices:**
-
+
1. **Input Validation for URLs:**
- Always validate any user-supplied URL or URL components
- Use `\Drupal\Component\Utility\UrlHelper::isValid()` to validate URLs
- Implement allowlists rather than blocklists for domains/IPs
- Parse URLs and validate each component (protocol, domain, port, path)
-
+
2. **Network-Level Controls:**
- Implement network-level access controls for internal services
- Use application firewalls to restrict outbound connections
- Configure proxies to control and monitor outbound requests
- Segment sensitive internal services from public-facing applications
-
+
3. **Request Handling:**
- Avoid passing raw user input to HTTP clients
- Set reasonable timeouts for all HTTP requests
- Disable HTTP redirects or limit redirect chains
- Validate response types match expected formats
- Use dedicated service accounts with minimal privileges for API calls
-
+
4. **Drupal-Specific Controls:**
- Utilize Drupal's built-in UrlHelper class for URL validation
- Configure Guzzle HTTP client with appropriate security options
- Consider using middleware to enforce URL validation
- Use Drupal's logging system to record suspicious outbound requests
- Implement specific content security policies
-
+
5. **Authentication and Access Controls:**
- Implement proper authentication for internal service calls
- Use context-specific API tokens with limited privileges
@@ -100,15 +100,15 @@ actions:
# Check 1: Proper URL validation
- pattern: "UrlHelper::isValid\\([^)]+\\)"
message: "Using proper URL validation with UrlHelper."
-
+
# Check 2: Allowlisting domains
- pattern: "array_intersect|in_array|allowlist|whitelist"
message: "Implementing domain/URL allowlisting for outbound requests."
-
+
# Check 3: Safe XML processing
- pattern: "libxml_disable_entity_loader\\(true\\)"
message: "Properly disabling XML external entities."
-
+
# Check 4: Using Drupal's HTTP client safely
- pattern: "\\\\Drupal::httpClient\\(\\)[^;]*\\$options"
message: "Using Drupal's HTTP client with explicit options."
@@ -133,4 +133,6 @@ metadata:
- "https://www.drupal.org/docs/develop/security-in-drupal/writing-secure-code-for-drupal"
- "https://portswigger.net/web-security/ssrf"
- "https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html"
-
+```
+
+
diff --git a/.cursor/rules/drupal-vulnerable-components.mdc b/.cursor/rules/drupal-vulnerable-components.mdc
index 96975a7..0a47018 100644
--- a/.cursor/rules/drupal-vulnerable-components.mdc
+++ b/.cursor/rules/drupal-vulnerable-components.mdc
@@ -7,7 +7,7 @@ alwaysApply: false
This rule enforces security best practices to prevent vulnerabilities related to outdated or vulnerable components in Drupal applications, as defined in OWASP Top 10:2021-A06.
-
+```yaml
name: drupal_vulnerable_components
description: Detect and prevent vulnerabilities related to outdated or vulnerable components in Drupal as defined in OWASP Top 10:2021-A06
filters:
@@ -22,39 +22,39 @@ actions:
# Pattern 1: Outdated Drupal core version declaration
- pattern: "core:\\s*('|\")8\\.[0-6](mdc:'|\")|core_version_requirement:\\s*('|\")[^9].+('|\")"
message: "Potentially outdated Drupal core version detected. Consider upgrading to the latest secure version of Drupal 9 or 10."
-
+
# Pattern 2: Usage of deprecated functions
- pattern: "drupal_set_message\\(|format_date\\(|drupal_render\\(|entity_load\\(|variable_get\\(|variable_set\\("
message: "Deprecated function detected. Use modern replacements to ensure compatibility and security updates."
-
+
# Pattern 3: Known vulnerable libraries referenced
- pattern: "jquery\\.min\\.js\\?v=1\\.|jquery-1\\.|jquery-2\\.|ckeditor/|tinymce/|angular\\.js@1\\."
message: "Potentially vulnerable JavaScript library version detected. Update to the latest secure version."
-
+
# Pattern 4: Direct inclusion of external scripts without SRI
- pattern: "
```
-
+
```javascript
// Programmatically adding a script with SRI
function addScriptWithIntegrity(url, integrity) {
@@ -148,7 +148,7 @@ actions:
document.head.appendChild(script);
}
```
-
+
3. **Dependency Verification:**
- Use npm/yarn audit regularly
- Implement lockfiles and version pinning
@@ -163,7 +163,7 @@ actions:
}
}
```
-
+
```javascript
// Automated dependency verification in CI/CD
// .github/workflows/security.yml
@@ -179,7 +179,7 @@ actions:
// node-version: '16'
// - run: npm audit
```
-
+
4. **Secure Object Handling:**
- Prevent prototype pollution
- Use Object.create(null) for empty objects
@@ -189,31 +189,31 @@ actions:
function safeObjectMerge(target, source) {
// Start with a null prototype object
const result = Object.create(null);
-
+
// Copy properties from target
for (const key in target) {
- if (Object.prototype.hasOwnProperty.call(target, key) &&
- key !== '__proto__' &&
- key !== 'constructor' &&
+ if (Object.prototype.hasOwnProperty.call(target, key) &&
+ key !== '__proto__' &&
+ key !== 'constructor' &&
key !== 'prototype') {
result[key] = target[key];
}
}
-
+
// Copy properties from source
for (const key in source) {
- if (Object.prototype.hasOwnProperty.call(source, key) &&
- key !== '__proto__' &&
- key !== 'constructor' &&
+ if (Object.prototype.hasOwnProperty.call(source, key) &&
+ key !== '__proto__' &&
+ key !== 'constructor' &&
key !== 'prototype') {
result[key] = source[key];
}
}
-
+
return result;
}
```
-
+
5. **Secure Dynamic Imports:**
- Validate module paths before importing
- Use allowlists for dynamic imports
@@ -225,12 +225,12 @@ actions:
'./components/footer',
'./components/sidebar'
];
-
+
async function safeImport(modulePath) {
if (!ALLOWED_MODULES.includes(modulePath)) {
throw new Error(`Module ${modulePath} is not in the allowlist`);
}
-
+
try {
return await import(modulePath);
} catch (error) {
@@ -239,7 +239,7 @@ actions:
}
}
```
-
+
6. **CI/CD Pipeline Security:**
- Implement integrity checks in build pipelines
- Verify dependencies and artifacts
@@ -274,7 +274,7 @@ actions:
dist
dist/integrity.txt
```
-
+
7. **Secure Update Mechanisms:**
- Verify integrity of updates before applying
- Use digital signatures when possible
@@ -282,22 +282,22 @@ actions:
```javascript
import crypto from 'crypto';
import fs from 'fs';
-
+
async function verifyUpdate(updateFile, signatureFile, publicKeyFile) {
try {
const updateData = fs.readFileSync(updateFile);
const signature = fs.readFileSync(signatureFile);
const publicKey = fs.readFileSync(publicKeyFile);
-
+
const verify = crypto.createVerify('SHA256');
verify.update(updateData);
-
+
const isValid = verify.verify(publicKey, signature);
-
+
if (!isValid) {
throw new Error('Update signature verification failed');
}
-
+
return { valid: true, data: updateData };
} catch (error) {
console.error('Update verification failed:', error);
@@ -305,7 +305,7 @@ actions:
}
}
```
-
+
8. **Plugin/Extension Security:**
- Implement allowlists for plugins
- Verify plugin integrity before loading
@@ -316,20 +316,20 @@ actions:
this.plugins = new Map();
this.allowedPlugins = new Set(['logger', 'analytics', 'theme']);
}
-
+
async registerPlugin(name, pluginPath, expectedHash) {
if (!this.allowedPlugins.has(name)) {
throw new Error(`Plugin ${name} is not in the allowlist`);
}
-
+
// Verify plugin integrity
const pluginCode = await fetch(pluginPath).then(r => r.text());
const hash = crypto.createHash('sha256').update(pluginCode).digest('hex');
-
+
if (hash !== expectedHash) {
throw new Error(`Plugin integrity check failed for ${name}`);
}
-
+
// Safe loading using Function constructor instead of eval
// Still has security implications but better than direct eval
const sandboxedPlugin = new Function('exports', 'require', pluginCode);
@@ -342,14 +342,14 @@ actions:
}
return require(module);
};
-
+
sandboxedPlugin(exports, safeRequire);
this.plugins.set(name, exports);
return exports;
}
}
```
-
+
9. **Secure Data Binding:**
- Avoid eval() and new Function()
- Use template literals or frameworks with safe binding
@@ -360,20 +360,20 @@ actions:
// const element = document.getElementById(id);
// element.innerHTML = eval('`' + template + '`'); // DANGEROUS!
// }
-
+
// Safe alternative:
function updateElement(id, data) {
const element = document.getElementById(id);
-
+
// Use a template literal with explicit interpolation
const template = `
${escapeHTML(data.name)}
${escapeHTML(data.bio)}
`;
-
+
element.innerHTML = template;
}
-
+
function escapeHTML(str) {
return str
.replace(/&/g, '&')
@@ -383,7 +383,7 @@ actions:
.replace(/'/g, ''');
}
```
-
+
10. **Secure Configuration Management:**
- Validate configurations before use
- Use schema validation for config files
@@ -391,7 +391,7 @@ actions:
```javascript
import Ajv from 'ajv';
import fs from 'fs';
-
+
function loadAndValidateConfig(configPath) {
// Define schema for configuration
const configSchema = {
@@ -417,14 +417,14 @@ actions:
required: ['server', 'database'],
additionalProperties: false
};
-
+
try {
const configData = fs.readFileSync(configPath, 'utf8');
const config = JSON.parse(configData);
-
+
const ajv = new Ajv({ allErrors: true });
const validate = ajv.compile(configSchema);
-
+
if (validate(config)) {
return { valid: true, config };
} else {
@@ -435,7 +435,7 @@ actions:
}
}
```
-
+
11. **Secure Webpack Configuration:**
- Enable SRI in webpack
- Use content hashing for cache busting
@@ -443,7 +443,7 @@ actions:
```javascript
// webpack.config.js
const SubresourceIntegrityPlugin = require('webpack-subresource-integrity');
-
+
module.exports = {
output: {
filename: '[name].[contenthash].js',
@@ -457,7 +457,7 @@ actions:
]
};
```
-
+
12. **Secure npm/yarn Configuration:**
- Enable integrity checks
- Use lockfiles and exact versions
@@ -468,13 +468,13 @@ actions:
audit-level=moderate
save-exact=true
verify-store=true
-
+
# .yarnrc.yml
enableStrictSsl: true
enableImmutableInstalls: true
checksumBehavior: "throw"
```
-
+
13. **Secure JSON Parsing:**
- Use reviver functions with JSON.parse
- Example:
@@ -485,19 +485,19 @@ actions:
if (key === 'role' && !['user', 'admin', 'editor'].includes(value)) {
return 'user'; // Default to safe value
}
-
+
// Prevent Date objects from being reconstructed from strings
- if (typeof value === 'string' &&
+ if (typeof value === 'string' &&
/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$/.test(value)) {
// Return as string, not Date object
return value;
}
-
+
return value;
});
}
```
-
+
14. **Content Security Policy (CSP):**
- Implement strict CSP headers
- Use nonce-based CSP for inline scripts
@@ -506,13 +506,13 @@ actions:
// Express.js example
import crypto from 'crypto';
import helmet from 'helmet';
-
+
app.use((req, res, next) => {
// Generate a new nonce for each request
res.locals.cspNonce = crypto.randomBytes(16).toString('base64');
next();
});
-
+
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
@@ -525,13 +525,13 @@ actions:
// Add other directives as needed
}
}));
-
+
// In your template engine, use the nonce:
//
```
-
+
15. **Secure Local Storage:**
- Validate data before storing and after retrieving
- Consider encryption for sensitive data
@@ -543,7 +543,7 @@ actions:
constructor(secret) {
this.secret = secret;
}
-
+
// Set item with validation and encryption
setItem(key, value, schema) {
// Validate with schema if provided
@@ -554,22 +554,22 @@ actions:
throw new Error(`Invalid data for ${key}: ${ajv.errorsText(validate.errors)}`);
}
}
-
+
// Simple encryption (not for truly sensitive data)
const valueStr = JSON.stringify(value);
const encrypted = this.encrypt(valueStr);
localStorage.setItem(key, encrypted);
}
-
+
// Get item with decryption and validation
getItem(key, schema) {
const encrypted = localStorage.getItem(key);
if (!encrypted) return null;
-
+
try {
const decrypted = this.decrypt(encrypted);
const value = JSON.parse(decrypted);
-
+
// Validate with schema if provided
if (schema) {
const ajv = new Ajv();
@@ -579,14 +579,14 @@ actions:
return null;
}
}
-
+
return value;
} catch (error) {
console.error(`Failed to retrieve ${key}:`, error);
return null;
}
}
-
+
// Simple XOR encryption (not for production use with sensitive data)
encrypt(text) {
let result = '';
@@ -595,7 +595,7 @@ actions:
}
return btoa(result);
}
-
+
decrypt(encoded) {
const text = atob(encoded);
let result = '';
@@ -612,20 +612,20 @@ actions:
# Check 1: Subresource Integrity
- pattern: "
```
-
+
4. **Automated Security Scanning:**
- Integrate security scanning into your CI/CD pipeline
- Example GitHub Actions workflow:
```yaml
name: Security Scan
-
+
on:
push:
branches: [ main ]
@@ -145,7 +145,7 @@ actions:
branches: [ main ]
schedule:
- cron: '0 0 * * 0' # Run weekly
-
+
jobs:
security:
runs-on: ubuntu-latest
@@ -165,7 +165,7 @@ actions:
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
```
-
+
5. **Dependency Pinning:**
- Pin dependencies to specific versions to prevent unexpected updates
- Example:
@@ -178,44 +178,44 @@ actions:
}
}
```
-
+
6. **Deprecated API Replacement:**
- Replace deprecated Node.js APIs with modern alternatives
- Example:
```javascript
// INSECURE: Using deprecated Buffer constructor
const buffer = new Buffer(data);
-
+
// SECURE: Using Buffer.from()
const buffer = Buffer.from(data);
-
+
// INSECURE: Using deprecated crypto methods
const crypto = require('crypto');
const cipher = crypto.createCipher('aes-256-cbc', key);
-
+
// SECURE: Using modern crypto methods
const crypto = require('crypto');
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
```
-
+
7. **Browser API Modernization:**
- Replace deprecated browser APIs with modern alternatives
- Example:
```javascript
// INSECURE: Using document.write
document.write('Hello World
');
-
+
// SECURE: Using DOM manipulation
document.getElementById('content').innerHTML = 'Hello World
';
-
+
// INSECURE: Using escape/unescape
const encoded = escape(data);
-
+
// SECURE: Using encodeURIComponent
const encoded = encodeURIComponent(data);
```
-
+
8. **Safe Dynamic Imports:**
- Avoid dynamic imports with variable concatenation
- Example:
@@ -223,25 +223,25 @@ actions:
// INSECURE: Dynamic import with concatenation
const moduleName = userInput;
import('./' + moduleName + '.js');
-
+
// SECURE: Validate input against a whitelist
const validModules = ['module1', 'module2', 'module3'];
if (validModules.includes(moduleName)) {
import(`./${moduleName}.js`);
}
```
-
+
9. **Regular Expression Safety:**
- Avoid vulnerable regex patterns that could lead to ReDoS attacks
- Example:
```javascript
// INSECURE: Vulnerable regex pattern
const regex = /^(a+)+$/;
-
+
// SECURE: Optimized regex pattern
const regex = /^a+$/;
```
-
+
10. **Vendor Management:**
- Evaluate the security posture of third-party libraries before use
- Prefer libraries with active maintenance and security focus
@@ -252,7 +252,7 @@ actions:
- Is there a responsible disclosure process?
- How many open issues and pull requests exist?
- What is the download count and GitHub stars?
-
+
11. **Runtime Dependency Checking:**
- Implement runtime checks for critical dependencies
- Example:
@@ -261,7 +261,7 @@ actions:
try {
const packageJson = require('some-critical-package/package.json');
const semver = require('semver');
-
+
if (semver.lt(packageJson.version, '2.0.0')) {
console.warn('Warning: Using a potentially vulnerable version of some-critical-package');
}
@@ -269,7 +269,7 @@ actions:
console.error('Error checking package version:', err);
}
```
-
+
12. **Minimal Dependencies:**
- Minimize the number of dependencies to reduce attack surface
- Regularly audit and remove unused dependencies
@@ -277,7 +277,7 @@ actions:
```bash
# Find unused dependencies
npx depcheck
-
+
# Analyze your bundle size
npx webpack-bundle-analyzer
```
@@ -287,19 +287,19 @@ actions:
# Check 1: Using npm audit
- pattern: "\"scripts\"\\s*:\\s*\\{[^}]*?\"audit\"\\s*:\\s*\"npm audit"
message: "Using npm audit to check for vulnerabilities."
-
+
# Check 2: Using lock files
- pattern: "package-lock\\.json|yarn\\.lock|pnpm-lock\\.yaml"
message: "Using lock files to ensure dependency consistency."
-
+
# Check 3: Using integrity hashes
- pattern: "integrity=['\"]sha\\d+-[A-Za-z0-9+/=]+['\"]"
message: "Using subresource integrity hashes for external resources."
-
+
# Check 4: Using modern Buffer API
- pattern: "Buffer\\.(?:from|alloc|allocUnsafe)"
message: "Using modern Buffer API instead of deprecated constructor."
-
+
# Check 5: Using dependency scanning in CI
- pattern: "npm\\s+audit|snyk\\s+test|yarn\\s+audit"
location: "(?:\\.github/workflows|\\.gitlab-ci\\.yml|Jenkinsfile|azure-pipelines\\.yml)"
@@ -333,4 +333,6 @@ metadata:
- "https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity"
- "https://github.com/OWASP/NodeGoat"
- "https://owasp.org/www-project-dependency-check/"
-
+```
+
+
diff --git a/.cursor/rules/lagoon-docker-compose-standards.mdc b/.cursor/rules/lagoon-docker-compose-standards.mdc
index dfb5a29..76c25b9 100644
--- a/.cursor/rules/lagoon-docker-compose-standards.mdc
+++ b/.cursor/rules/lagoon-docker-compose-standards.mdc
@@ -6,7 +6,7 @@ globs: docker-compose.yml, docker-compose.*.yml
Ensures proper Docker Compose configuration for Lagoon deployments, following best practices and Lagoon-specific requirements.
-
+```yaml
name: lagoon_docker_compose_standards
description: Enforce standards for Lagoon Docker Compose files
filters:
@@ -24,14 +24,14 @@ actions:
- pattern: "volumes:\\s+[^:]+:\\s+(?!.*delegated)"
message: "Use 'delegated' mount consistency for better performance on macOS development environments"
-
+
- pattern: "services:\\s+\\w+:\\s+(?!.*restart:)"
message: "Define restart policy for services to ensure proper behavior during deployment"
- type: suggest
message: |
## Lagoon Docker Compose Best Practices:
-
+
### Service Configuration
- Define service types via labels (e.g., `lagoon.type: nginx`)
- Use proper image naming conventions (e.g., `amazeeio/nginx-drupal:latest`)
@@ -39,18 +39,18 @@ actions:
- Define health checks for critical services
- Configure proper networking with Lagoon defaults
- Set resource constraints appropriate for each environment
-
+
### Volume Configuration
- Use named volumes for persistent data
- Configure appropriate volume mounts with correct permissions
- Use 'delegated' mount consistency for macOS performance
- Avoid mounting the entire codebase when possible
-
+
### Build Configuration
- Use build arguments appropriately
- Define proper Dockerfile paths
- Use multi-stage builds for smaller images
-
+
### Example Service Configuration:
```yaml
services:
@@ -79,14 +79,16 @@ actions:
- pattern: "networks:\\s+(?!.*default:)"
message: "Configure proper network settings for Lagoon compatibility and service communication"
-
+
- pattern: "services:\\s+mariadb:\\s+(?!.*image:\\s+amazeeio\\/mariadb)"
message: "Use Lagoon-provided MariaDB image for compatibility with Lagoon environment"
-
+
- pattern: "services:\\s+\\w+:\\s+environment:\\s+(?!.*\\$\\{LAGOON)"
message: "Use Lagoon environment variables with fallbacks for local development"
metadata:
priority: high
version: 1.1
-
\ No newline at end of file
+```
+
+
diff --git a/.cursor/rules/lagoon-yml-standards.mdc b/.cursor/rules/lagoon-yml-standards.mdc
index 0daa2ac..e585673 100644
--- a/.cursor/rules/lagoon-yml-standards.mdc
+++ b/.cursor/rules/lagoon-yml-standards.mdc
@@ -6,7 +6,7 @@ globs: .lagoon.yml, .lagoon.*.yml
Ensures proper configuration and best practices for Lagoon deployment files, focusing on environment configuration, routes, tasks, and deployment workflows.
-
+```yaml
name: lagoon_yml_standards
description: Enforce standards for Lagoon configuration files
filters:
@@ -29,39 +29,39 @@ actions:
- pattern: "cronjobs:\\s*-\\s*name:[^\\n]*\\n\\s*schedule:\\s*'\\*\\s*\\*'"
message: "Use 'M' or 'H' notation for randomized cron scheduling to prevent server load spikes"
-
+
- pattern: "routes:\\s*-\\s*\\w+:\\s*-[^:]+:\\s*(?!.*redirects:)"
message: "Consider configuring redirects for routes to handle legacy URLs or domain migrations"
- type: suggest
message: |
## Lagoon Configuration Best Practices:
-
+
### Environment Configuration
- Use environment-specific configurations for different deployment targets
- Define environment types for proper resource allocation
- Configure environment variables specific to each environment
- Use environment-specific routes and domains
-
+
### Routes Configuration
- Configure routes with appropriate SSL settings
- Set up redirects for legacy URLs
- Configure proper insecure traffic handling (Allow or Redirect)
- Use wildcard domains for feature branch environments
-
+
### Tasks Configuration
- Implement proper pre-rollout tasks with error handling
- Configure post-rollout tasks with appropriate conditions
- Use conditional task execution based on environment
- Include database sync in PR environments
- Implement proper backup strategies before major changes
-
+
### Cron Configuration
- Use randomized cron schedules with 'M' and 'H' notation
- Set appropriate frequency for different tasks
- Ensure cron jobs have proper error handling
- Use descriptive names for cron jobs
-
+
### Example Configuration:
```yaml
environments:
@@ -108,14 +108,16 @@ actions:
- pattern: "routes:\\s*-\\s*\\w+:\\s*-[^:]+:\\s*insecure:\\s*(Allow|Redirect)"
message: "Configure proper insecure traffic handling to ensure secure access to your application"
-
+
- pattern: "(?!.*backup-strategy:)"
message: "Consider implementing a backup strategy for critical environments to prevent data loss"
-
+
- pattern: "cronjobs:\\s*-\\s*name:[^\\n]*\\n\\s*schedule:[^\\n]*\\n\\s*(?!.*service:)"
message: "Specify the service for cron jobs to ensure they run in the correct container"
metadata:
priority: critical
version: 1.1
-
\ No newline at end of file
+```
+
+
diff --git a/.cursor/rules/multi-agent-coordination.mdc b/.cursor/rules/multi-agent-coordination.mdc
index 7ba3a9f..334db34 100644
--- a/.cursor/rules/multi-agent-coordination.mdc
+++ b/.cursor/rules/multi-agent-coordination.mdc
@@ -6,7 +6,7 @@ globs: *.php, *.js, *.ts, *.vue, *.jsx, *.tsx
Ensures consistent coordination between different AI agents and roles.
-
+```yaml
name: multi_agent_coordination
description: Enforce standards for multi-agent coordination and workflow
filters:
@@ -42,4 +42,6 @@ actions:
metadata:
priority: high
version: 1.0
-
\ No newline at end of file
+```
+
+
diff --git a/.cursor/rules/new-pull-request.mdc b/.cursor/rules/new-pull-request.mdc
index 2953f8a..c04b07a 100644
--- a/.cursor/rules/new-pull-request.mdc
+++ b/.cursor/rules/new-pull-request.mdc
@@ -1,6 +1,6 @@
---
description: Use this rule when requested to review a pull request
-globs:
+globs:
alwaysApply: false
---
# Code Review Agent Instructions
@@ -10,7 +10,7 @@ You are a senior technical lead and architect conducting automated code reviews
## Primary Objectives
1. **Requirement Fulfilment Analysis (50%)**: Verify code changes satisfy issue requirements
-2. **Code Standards Compliance (30%)**: Ensure adherence to technology-specific coding standards and best practices
+2. **Code Standards Compliance (30%)**: Ensure adherence to technology-specific coding standards and best practices
3. **Security Assessment (20%)**: Validate OWASP security standards and framework-specific security practices
4. **Label Management**: Apply appropriate GitHub labels for workflow automation
5. **Freshdesk Integration**: Update issues with structured review findings and log time entry
@@ -22,7 +22,7 @@ You are a senior technical lead and architect conducting automated code reviews
- If not provided during the prompt, ask user to provide PR number or URL, extract and analyse:
### Pull Request Context
-- **PR Details**: Extract PR number
+- **PR Details**: Extract PR number
- **Repository Info**: Note owner, repo name, and branch information
- **Change Statistics**: Review additions, deletions, and changed files count
- **Use GitHub mcp tool**: Use github-mcp tool to connect to GitHub. If fails, Use gh cli.
@@ -33,7 +33,7 @@ You are a senior technical lead and architect conducting automated code reviews
- **Acceptance Criteria**: Identify specific acceptance criteria from issue conversations
- **Client Feedback**: Review conversation history for clarification and changes
- **Technical Context**: Note technology stack, modules affected, and dependencies
-- **Extract issue information**: Check PR description and title to pull issue number.
+- **Extract issue information**: Check PR description and title to pull issue number.
In most cases it will be a Freshdesk issue. Use freshdesk-mcp task get issue information,
conversations and issue summary to understand context of the issue.
@@ -213,7 +213,7 @@ Compare code changes against:
]
}
EOF
-
+
# Submit the review
gh api repos/{owner}/{repo}/pulls/{pr_number}/reviews -X POST --input /tmp/review_comments.json
```
@@ -295,7 +295,7 @@ Compare code changes against:
**Auto-Apply Labels Based On:**
- **Score ≥ 80%**: Add `code-review-approved`
-- **Score < 80%**: Add `code-review-changes`
+- **Score < 80%**: Add `code-review-changes`
- **Security Issues**: Add `code-review-security`
- **Standards Violations**: Add `drupal-standards`
- **Requirement Score ≥ 80%**: Add `requirements-met`
@@ -366,7 +366,7 @@ After completing the code review, perform the following Freshdesk updates:
**Status Colours:**
- **Success/Approved**: `#1f7a1f` (dark green)
-- **Warning/Changes Needed**: `#cc8800` (dark orange)
+- **Warning/Changes Needed**: `#cc8800` (dark orange)
- **Critical/Failed**: `#dc3545` (red)
- **Info/In Progress**: `#17a2b8` (blue)
diff --git a/.cursor/rules/node-dependencies.mdc b/.cursor/rules/node-dependencies.mdc
index 07c2e63..ce5a14c 100644
--- a/.cursor/rules/node-dependencies.mdc
+++ b/.cursor/rules/node-dependencies.mdc
@@ -6,7 +6,7 @@ globs: package.json, .nvmrc
Ensures correct Node.js versions and package management.
-
+```yaml
name: node_dependency_management
description: Enforce Node.js versioning and package management best practices.
filters:
@@ -32,4 +32,5 @@ actions:
metadata:
priority: medium
version: 1.0
-
+```
+
diff --git a/.cursor/rules/php-drupal-best-practices.mdc b/.cursor/rules/php-drupal-best-practices.mdc
index 0627e1b..d3bc4a7 100644
--- a/.cursor/rules/php-drupal-best-practices.mdc
+++ b/.cursor/rules/php-drupal-best-practices.mdc
@@ -6,7 +6,7 @@ globs: *.php, *.module, *.theme, *.inc, *.info, *.install
Defines comprehensive coding standards and best practices for PHP and Drupal development, with a focus on modern PHP features, Drupal 10+ standards, and modularity.
-
+```yaml
name: enhanced_php_drupal_best_practices
description: Enforce PHP 8.3+ features, Drupal 10+ coding standards, and modularity
filters:
@@ -53,114 +53,114 @@ actions:
- pattern: "\\$this->config\\('\\w+'\\)"
message: "Use ConfigFactory for configuration management."
-
+
- pattern: "array\\s*\\("
message: "Use short array syntax ([]) instead of array() for consistent code style."
-
+
- pattern: "(?get\\([^)]+\\)->getValue\\(\\)"
message: "Use $entity->get('field_name')->value instead of getValue() when possible."
-
+
- pattern: "\\bvar_dump\\b|\\bprint_r\\b|\\bdump\\b"
message: "Don't use debug functions in production code; use Drupal's logger instead."
-
+
- pattern: "\\bnew\\s+DateTime\\b"
message: "Use Drupal's DateTimeInterface and DrupalDateTime instead of PHP's DateTime."
-
+
- pattern: "\\beval\\b"
message: "Never use eval() as it poses security risks."
-
+
- pattern: "function\\s+\\w+_menu_callback\\("
message: "Use controller classes with route definitions instead of hook_menu() callbacks."
-
+
- pattern: "\\/\\*\\*(?:[^*]|\\*[^/])*?@file(?:[^*]|\\*[^/])*?\\*\\/"
message: "All PHP files must include proper @file documentation in the docblock."
-
+
- pattern: "function\\s+\\w+\\s*\\((?:[^)]|\\([^)]*\\))*\\)\\s*\\{(?:[^}]|\\{[^}]*\\})*\\$_SESSION"
message: "Use Drupal's user session handling instead of $_SESSION."
-
+
- pattern: "function\\s+theme_\\w+\\("
message: "Theme functions should be replaced with Twig templates in Drupal 8+."
-
+
- pattern: "drupal_add_js|drupal_add_css"
message: "Use #attached in render arrays instead of drupal_add_js() or drupal_add_css()."
-
+
- pattern: "function\\s+\\w+_implements_hook_\\w+\\("
message: "Use proper hook implementation format: module_name_hook_name()."
-
+
- pattern: "use\\s+[^;]+,\\s*[^;]+"
message: "Specify a single class per use statement. Do not specify multiple classes in a single use statement."
-
+
- pattern: "use\\s+\\\\[A-Za-z]"
message: "When importing a class with 'use', do not include a leading backslash (\\)."
-
+
- pattern: "\\bnew\\s+\\\\DateTime\\(\\)"
message: "Non-namespaced global classes (like Exception) must be fully qualified with a leading backslash (\\) when used in a namespaced file."
-
+
- pattern: "(?attributes->set\\('([^_][^']*)',"
message: "Request attributes added by modules should be prefixed with underscore (e.g., '_context_value')."
-
+
- pattern: "\\\\Drupal::request\\(\\)->attributes->get\\('(_(system_path|title|route|route_object|controller|content|account))'\\)"
message: "Avoid overwriting reserved Symfony or Drupal core request attributes."
-
+
- pattern: "(?attributes->set('_context_value', $myvalue);
-
+
// Correctly retrieving a request attribute
$contextValue = \Drupal::request()->attributes->get('_context_value');
```
@@ -446,56 +446,57 @@ actions:
- pattern: "try\\s*\\{[^}]*\\}\\s*catch\\s*\\([^)]*\\)\\s*\\{\\s*\\}"
message: "Implement proper exception handling in catch blocks."
-
+
- pattern: "namespace\\s+Drupal\\\\(?!\\w+\\\\)"
message: "Namespace should be Drupal\\ModuleName\\..."
-
+
- pattern: "class\\s+[^\\s]+\\s+implements\\s+[^\\s]+Interface"
message: "Follow PSR-4 for class naming and organization."
-
+
- pattern: "\\*\\s+@return\\s+[a-z]+\\|null"
message: "Use nullable return types (e.g., ?string) instead of type|null in docblocks."
-
+
- pattern: "function\\s+__construct\\([^)]*\\)\\s*\\{[^}]*parent::"
message: "Call parent::__construct() if extending a class with a constructor."
-
+
- pattern: "function\\s+[gs]et[A-Z]\\w+\\("
message: "Use camelCase for method names (e.g., getId instead of get_id)."
-
+
- pattern: "\\/\\*\\*(?:(?!\\@file).)*?\\*\\/"
message: "Add proper @file docblock for PHP files."
-
+
- pattern: "function\\s+hook_[a-z0-9_]+\\("
message: "Replace 'hook_' prefix with your module name in hook implementations."
-
+
- pattern: "(?
\ No newline at end of file
+```
+
diff --git a/.cursor/rules/php-drupal-development-standards.mdc b/.cursor/rules/php-drupal-development-standards.mdc
index 3d600f6..16ababd 100644
--- a/.cursor/rules/php-drupal-development-standards.mdc
+++ b/.cursor/rules/php-drupal-development-standards.mdc
@@ -6,7 +6,7 @@ globs: *.php, *.module, *.inc, *.install, *.theme
Ensures adherence to PHP 8.3+ features and Drupal development best practices for improved code quality, security, and maintainability.
-
+```yaml
name: enhanced_php_drupal_development_standards
description: Enforce PHP 8.3+ and Drupal development standards
filters:
@@ -84,4 +84,5 @@ actions:
metadata:
priority: critical
version: 1.1
-
\ No newline at end of file
+```
+
diff --git a/.cursor/rules/php-memory-optimisation.mdc b/.cursor/rules/php-memory-optimisation.mdc
index 6c55571..ebf1dfa 100644
--- a/.cursor/rules/php-memory-optimisation.mdc
+++ b/.cursor/rules/php-memory-optimisation.mdc
@@ -6,7 +6,7 @@ globs: *.php, *.ini
Guidance and automated checks to reduce peak memory usage in PHP applications. Based on widely accepted practices and the article "PHP Memory Optimization Tips" by Khouloud Haddad.
-
+```yaml
name: php_memory_optimisation
description: Detect memory-heavy patterns and suggest streaming, generators, and better data handling
filters:
@@ -56,7 +56,7 @@ actions:
metadata:
priority: high
version: 1.0
-
+```
name: php_ini_opcache_recommendations
diff --git a/.cursor/rules/project-definition-template.mdc b/.cursor/rules/project-definition-template.mdc
index 2d6eddb..c93acae 100644
--- a/.cursor/rules/project-definition-template.mdc
+++ b/.cursor/rules/project-definition-template.mdc
@@ -6,7 +6,7 @@ globs: README.md, /docs/*
This rule enforces best practices for documenting project context, ensuring clarity and maintainability through well-documented README files and documentation.
-
+```yaml
name: comprehensive_project_definition
description: Enforce comprehensive project context definition for CursorAI
filters:
@@ -76,4 +76,5 @@ actions:
metadata:
priority: medium
version: 1.1
-
\ No newline at end of file
+```
+
diff --git a/.cursor/rules/pull-request-changelist-instructions.mdc b/.cursor/rules/pull-request-changelist-instructions.mdc
index 42590e2..e2d645d 100644
--- a/.cursor/rules/pull-request-changelist-instructions.mdc
+++ b/.cursor/rules/pull-request-changelist-instructions.mdc
@@ -1,6 +1,6 @@
---
description: Guidelines for creating consistent pull request changelists in markdown format with proper code block formatting
-globs:
+globs:
alwaysApply: false
---
---
@@ -12,7 +12,7 @@ alwaysApply: false
This document outlines strict standards for creating and formatting pull request changelists in markdown. Following these guidelines ensures that the output remains as raw markdown (unrendered) and prevents any issues with Cursor’s markdown rendering.
-
+```yaml
name: pull_request_changelist_format
description: Updated guidelines for creating consistent pull request changelists in markdown with strict code block handling and structured formatting.
filters:
@@ -74,18 +74,18 @@ actions:
```
Adhering to these traditional, time-tested formatting guidelines not only prevents ambiguity but also paves the way for future improvements in automated changelist generation.
-
+
- type: validate
conditions:
- pattern: "^```\\s*markdown\\s*\\n#\\s+Summary\\s+of\\s+Changes"
message: "The changelist must be a raw markdown code block starting with '# Summary of Changes'. Ensure the use of triple backticks and correct heading structure."
- pattern: "-\\s+(Added|Updated|Removed)\\b"
message: "Each bullet point must begin with a past tense verb: 'Added', 'Updated', or 'Removed'."
-
+
examples:
- input: |
Request: "Create a PR changelist for my changes. Return markdown code as code."
-
+
Good Response from Cursor:
```markdown
# Summary of Changes
@@ -100,10 +100,10 @@ examples:
```
output: |
This is the correct format for Cursor to return a changelist – as a raw markdown code block enclosed in triple backticks.
-
+
- input: |
Request: "Create a PR changelist for my changes."
-
+
Bad Response from Cursor (rendered markdown instead of a code block):
# Summary of Changes
@@ -116,4 +116,5 @@ examples:
metadata:
priority: medium
version: 1.2
-
\ No newline at end of file
+```
+
diff --git a/.cursor/rules/python-authentication-failures.mdc b/.cursor/rules/python-authentication-failures.mdc
index b59062f..0fe0818 100644
--- a/.cursor/rules/python-authentication-failures.mdc
+++ b/.cursor/rules/python-authentication-failures.mdc
@@ -7,7 +7,7 @@ alwaysApply: false
This rule enforces security best practices to prevent identification and authentication failures in Python applications, as defined in OWASP Top 10:2021-A07.
-
+```yaml
name: python_authentication_failures
description: Detect and prevent identification and authentication failures in Python applications as defined in OWASP Top 10:2021-A07
filters:
@@ -22,59 +22,59 @@ actions:
# Pattern 1: Weak password validation
- pattern: "password\\s*=\\s*['\"][^'\"]{1,7}['\"]|min_length\\s*=\\s*[1-7]"
message: "Weak password policy detected. Passwords should be at least 8 characters long and include complexity requirements."
-
+
# Pattern 2: Hardcoded credentials
- pattern: "(username|user|login|password|passwd|pwd|secret|api_key|apikey|token)\\s*=\\s*['\"][^'\"]+['\"]"
message: "Hardcoded credentials detected. Store sensitive credentials in environment variables or a secure vault."
-
+
# Pattern 3: Missing password hashing
- pattern: "password\\s*=\\s*request\\.form\\[\\'password\\'\\]|password\\s*=\\s*request\\.POST\\.get\\(\\'password\\'\\)"
message: "Storing or comparing plain text passwords detected. Always hash passwords before storage or comparison."
-
+
# Pattern 4: Insecure password hashing
- pattern: "hashlib\\.md5\\(|hashlib\\.sha1\\(|hashlib\\.sha224\\("
message: "Insecure hashing algorithm detected. Use strong hashing algorithms like bcrypt, Argon2, or PBKDF2."
-
+
# Pattern 5: Missing brute force protection
- pattern: "@app\\.route\\(['\"]\\/(login|signin|authenticate)['\"]"
message: "Authentication endpoint detected without rate limiting or brute force protection. Implement account lockout or rate limiting."
-
+
# Pattern 6: Insecure session management
- pattern: "session\\[\\'user_id\\'\\]\\s*=|session\\[\\'authenticated\\'\\]\\s*=\\s*True"
message: "Session management detected. Ensure proper session security with secure cookies, proper expiration, and rotation."
-
+
# Pattern 7: Missing CSRF protection in authentication
- pattern: "form\\s*=\\s*FlaskForm|class\\s+\\w+Form\\(\\s*FlaskForm\\s*\\)|class\\s+\\w+Form\\(\\s*Form\\s*\\)"
message: "Form handling detected. Ensure CSRF protection is enabled for all authentication forms."
-
+
# Pattern 8: Insecure remember me functionality
- pattern: "remember_me|remember_token|stay_logged_in"
message: "Remember me functionality detected. Ensure secure implementation with proper expiration and refresh mechanisms."
-
+
# Pattern 9: Insecure password reset
- pattern: "@app\\.route\\(['\"]\\/(reset-password|forgot-password|recover)['\"]"
message: "Password reset functionality detected. Ensure secure implementation with time-limited tokens and proper user verification."
-
+
# Pattern 10: Missing multi-factor authentication
- pattern: "def\\s+login|def\\s+authenticate|def\\s+signin"
message: "Authentication function detected. Consider implementing multi-factor authentication for sensitive operations."
-
+
# Pattern 11: Insecure direct object reference in user management
- pattern: "User\\.objects\\.get\\(id=|User\\.query\\.get\\(|get_user_by_id\\("
message: "Direct user lookup detected. Ensure proper authorization checks before accessing user data."
-
+
# Pattern 12: Insecure JWT implementation
- pattern: "jwt\\.encode\\(|jwt\\.decode\\("
message: "JWT usage detected. Ensure proper signing, validation, expiration, and refresh mechanisms for JWTs."
-
+
# Pattern 13: Missing secure flag in cookies
- pattern: "set_cookie\\([^,]+,[^,]+,[^,]*secure=False|set_cookie\\([^,]+,[^,]+(?!,\\s*secure=True)"
message: "Cookie setting without secure flag detected. Set secure=True for all authentication cookies."
-
+
# Pattern 14: Missing HTTP-only flag in cookies
- pattern: "set_cookie\\([^,]+,[^,]+,[^,]*httponly=False|set_cookie\\([^,]+,[^,]+(?!,\\s*httponly=True)"
message: "Cookie setting without httponly flag detected. Set httponly=True for all authentication cookies."
-
+
# Pattern 15: Insecure default credentials
- pattern: "DEFAULT_USERNAME|DEFAULT_PASSWORD|ADMIN_USERNAME|ADMIN_PASSWORD"
message: "Default credential configuration detected. Remove default credentials from production code."
@@ -82,31 +82,31 @@ actions:
- type: suggest
message: |
**Python Authentication Security Best Practices:**
-
+
1. **Password Storage:**
- Use strong hashing algorithms with salting
- Implement proper work factors
- Example with passlib:
```python
from passlib.hash import argon2
-
+
# Hash a password
hashed_password = argon2.hash("user_password")
-
+
# Verify a password
is_valid = argon2.verify("user_password", hashed_password)
```
- Example with Django:
```python
from django.contrib.auth.hashers import make_password, check_password
-
+
# Hash a password
hashed_password = make_password("user_password")
-
+
# Verify a password
is_valid = check_password("user_password", hashed_password)
```
-
+
2. **Password Policies:**
- Enforce minimum length (at least 8 characters)
- Require complexity (uppercase, lowercase, numbers, special characters)
@@ -130,7 +130,7 @@ actions:
},
]
```
-
+
3. **Brute Force Protection:**
- Implement account lockout after failed attempts
- Use rate limiting for authentication endpoints
@@ -139,38 +139,38 @@ actions:
from flask import Flask
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
-
+
app = Flask(__name__)
limiter = Limiter(
app,
key_func=get_remote_address,
default_limits=["200 per day", "50 per hour"]
)
-
+
@app.route("/login", methods=["POST"])
@limiter.limit("5 per minute")
def login():
# Login logic here
pass
```
-
+
4. **Multi-Factor Authentication:**
- Implement MFA for sensitive operations
- Use time-based one-time passwords (TOTP)
- Example with pyotp:
```python
import pyotp
-
+
# Generate a secret key for the user
secret = pyotp.random_base32()
-
+
# Create a TOTP object
totp = pyotp.TOTP(secret)
-
+
# Verify a token
is_valid = totp.verify(user_provided_token)
```
-
+
5. **Secure Session Management:**
- Use secure, HTTP-only cookies
- Implement proper session expiration
@@ -178,7 +178,7 @@ actions:
- Example with Flask:
```python
from flask import Flask, session
-
+
app = Flask(__name__)
app.config.update(
SECRET_KEY='your-secret-key',
@@ -188,7 +188,7 @@ actions:
PERMANENT_SESSION_LIFETIME=timedelta(hours=1)
)
```
-
+
6. **CSRF Protection:**
- Implement CSRF tokens for all forms
- Validate tokens on form submission
@@ -196,15 +196,15 @@ actions:
```python
from flask_wtf import FlaskForm, CSRFProtect
from wtforms import StringField, PasswordField, SubmitField
-
+
csrf = CSRFProtect(app)
-
+
class LoginForm(FlaskForm):
username = StringField('Username')
password = PasswordField('Password')
submit = SubmitField('Login')
```
-
+
7. **Secure Password Reset:**
- Use time-limited, single-use tokens
- Send reset links to verified email addresses
@@ -212,20 +212,20 @@ actions:
```python
import secrets
from datetime import datetime, timedelta
-
+
def generate_reset_token(user_id):
token = secrets.token_urlsafe(32)
expiry = datetime.utcnow() + timedelta(hours=1)
# Store token and expiry in database with user_id
return token
-
+
def verify_reset_token(token):
# Retrieve token from database
# Check if token exists and is not expired
# If valid, return user_id
pass
```
-
+
8. **Secure JWT Implementation:**
- Use strong signing keys
- Include expiration claims
@@ -234,7 +234,7 @@ actions:
```python
import jwt
from datetime import datetime, timedelta
-
+
# Create a JWT
payload = {
'user_id': user.id,
@@ -242,7 +242,7 @@ actions:
'iat': datetime.utcnow()
}
token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')
-
+
# Verify a JWT
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
@@ -254,29 +254,29 @@ actions:
# Invalid token
pass
```
-
+
9. **Secure Cookie Configuration:**
- Set secure, HTTP-only, and SameSite flags
- Example with Flask:
```python
from flask import Flask, make_response
-
+
app = Flask(__name__)
-
+
@app.route('/set_cookie')
def set_cookie():
resp = make_response('Cookie set')
resp.set_cookie(
- 'session_id',
- 'value',
- secure=True,
- httponly=True,
+ 'session_id',
+ 'value',
+ secure=True,
+ httponly=True,
samesite='Lax',
max_age=3600
)
return resp
```
-
+
10. **Credential Storage:**
- Use environment variables or secure vaults
- Never hardcode credentials
@@ -284,9 +284,9 @@ actions:
```python
import os
from dotenv import load_dotenv
-
+
load_dotenv()
-
+
# Access credentials from environment variables
db_user = os.environ.get('DB_USER')
db_password = os.environ.get('DB_PASSWORD')
@@ -297,15 +297,15 @@ actions:
# Check 1: Proper password hashing
- pattern: "argon2|bcrypt|pbkdf2|make_password|generate_password_hash"
message: "Using secure password hashing algorithms."
-
+
# Check 2: CSRF protection
- pattern: "csrf|CSRFProtect|csrf_token|csrftoken"
message: "CSRF protection is implemented."
-
+
# Check 3: Secure cookie settings
- pattern: "SESSION_COOKIE_SECURE\\s*=\\s*True|secure=True|httponly=True|samesite"
message: "Secure cookie settings are configured."
-
+
# Check 4: Rate limiting
- pattern: "limiter\\.limit|RateLimitExceeded|rate_limit|throttle"
message: "Rate limiting is implemented for authentication endpoints."
@@ -335,4 +335,5 @@ metadata:
- "https://docs.djangoproject.com/en/stable/topics/auth/passwords/"
- "https://flask-login.readthedocs.io/en/latest/"
- "https://fastapi.tiangolo.com/tutorial/security/"
-
\ No newline at end of file
+```
+
diff --git a/.cursor/rules/python-broken-access-control.mdc b/.cursor/rules/python-broken-access-control.mdc
index 2ed05c7..69248b3 100644
--- a/.cursor/rules/python-broken-access-control.mdc
+++ b/.cursor/rules/python-broken-access-control.mdc
@@ -7,7 +7,7 @@ alwaysApply: false
This rule enforces security best practices to prevent broken access control vulnerabilities in Python applications, as defined in OWASP Top 10:2021-A01.
-
+```yaml
name: python_broken_access_control
description: Detect and prevent broken access control vulnerabilities in Python applications as defined in OWASP Top 10:2021-A01
filters:
@@ -22,39 +22,39 @@ actions:
# Pattern 1: Missing access control in Flask routes
- pattern: "@(app|blueprint)\\.route\\([^)]*\\)\\s*\\n\\s*def\\s+[a-zA-Z0-9_]+\\([^)]*\\):\\s*(?![^#]*@login_required|[^#]*current_user\\.|[^#]*session\\[)"
message: "Flask route lacks access control. Consider using @login_required or checking user permissions within the function."
-
+
# Pattern 2: Missing access control in Django views
- pattern: "class\\s+[A-Za-z0-9_]+View\\((?!LoginRequiredMixin|PermissionRequiredMixin|UserPassesTestMixin)[^)]*\\):"
message: "Django class-based view lacks access control mixins. Consider using LoginRequiredMixin, PermissionRequiredMixin, or UserPassesTestMixin."
-
+
# Pattern 3: Insecure direct object reference
- pattern: "(get|filter|find)_by_id\\(\\s*request\\.(GET|POST|args|form|json)\\[['\"][^'\"]+['\"]\\]\\s*\\)"
message: "Potential insecure direct object reference (IDOR). Validate that the current user has permission to access this object."
-
+
# Pattern 4: Hardcoded role checks
- pattern: "if\\s+user\\.role\\s*==\\s*['\"]admin['\"]|if\\s+user\\.(is_staff|is_superuser)\\s*:"
message: "Hardcoded role checks can be fragile. Consider using a permission system or role-based access control framework."
-
+
# Pattern 5: Missing authorization in FastAPI
- pattern: "@(app|router)\\.([a-z]+)\\([^)]*\\)\\s*\\n\\s*(?:async\\s+)?def\\s+[a-zA-Z0-9_]+\\([^)]*\\):\\s*(?![^#]*Depends\\(|[^#]*Security\\(|[^#]*HTTPBearer\\()"
message: "FastAPI endpoint lacks security dependencies. Consider using Depends(get_current_user) or similar security dependencies."
-
+
# Pattern 6: Bypassing access control with admin flags
- pattern: "if\\s+request\\.(GET|POST|args|form|json)\\[['\"]admin['\"]\\]|if\\s+request\\.(GET|POST|args|form|json)\\[['\"]debug['\"]\\]"
message: "Dangerous admin/debug flags in request parameters could bypass access control. Remove or secure these backdoors."
-
+
# Pattern 7: Insecure use of eval or exec with user input
- pattern: "eval\\(|exec\\(.*request\\."
message: "Extremely dangerous use of eval() or exec() with user input can lead to code execution. Avoid these functions entirely."
-
+
# Pattern 8: Missing access control in API endpoints
- pattern: "@api_view\\(|@api\\.route\\(|@app\\.api_route\\("
message: "API endpoint may lack access control. Ensure proper authentication and authorization checks are implemented."
-
+
# Pattern 9: Insecure Flask session usage
- pattern: "session\\[['\"][^'\"]+['\"]\\]\\s*=\\s*request\\."
message: "Setting session variables directly from request data without validation can lead to session-based access control bypasses."
-
+
# Pattern 10: Missing CSRF protection
- pattern: "class\\s+[A-Za-z0-9_]+Form\\((?!.*csrf).*\\):|@csrf_exempt"
message: "Form or view appears to be missing CSRF protection. Ensure CSRF tokens are properly implemented."
@@ -62,7 +62,7 @@ actions:
- type: suggest
message: |
**Python Access Control Best Practices:**
-
+
1. **Framework-Specific Controls:**
- **Django**: Use built-in authentication and permission decorators/mixins
- `@login_required`, `LoginRequiredMixin`
@@ -76,27 +76,27 @@ actions:
- `Depends(get_current_user)` pattern
- OAuth2 with `Security(oauth2_scheme)`
- JWT validation middleware
-
+
2. **General Access Control Principles:**
- Implement access control at the server side, never rely on client-side checks
- Use deny-by-default approach (whitelist vs blacklist)
- Implement proper session management
- Apply principle of least privilege
- Use contextual access control (time, location, device-based restrictions when appropriate)
-
+
3. **Object-Level Authorization:**
- Validate user has permission to access specific resources
- Implement row-level security for database access
- Use UUIDs instead of sequential IDs when possible
- Always verify ownership or permission before allowing operations on objects
-
+
4. **API Security:**
- Implement proper authentication for all API endpoints
- Use token-based authentication with proper validation
- Apply rate limiting to prevent brute force attacks
- Implement proper CORS configuration
- Log and monitor access control failures
-
+
5. **Testing Access Control:**
- Write tests specifically for authorization logic
- Test vertical access control (different permission levels)
@@ -108,15 +108,15 @@ actions:
# Check 1: Proper Django permission usage
- pattern: "@login_required|@permission_required|LoginRequiredMixin|PermissionRequiredMixin"
message: "Using Django's built-in access control mechanisms."
-
+
# Check 2: Proper Flask authentication
- pattern: "@login_required|current_user\\.is_authenticated|@auth\\.login_required"
message: "Implementing proper Flask authentication checks."
-
+
# Check 3: Object-level permission checks
- pattern: "\\.has_permission\\(|has_object_permission\\(|can_view\\(|can_edit\\("
message: "Implementing object-level permission checks."
-
+
# Check 4: FastAPI security dependencies
- pattern: "Depends\\(get_current_user\\)|Security\\(|HTTPBearer\\("
message: "Using FastAPI's security dependency injection."
@@ -146,4 +146,6 @@ metadata:
- https://flask-login.readthedocs.io/en/latest/
- https://fastapi.tiangolo.com/tutorial/security/
- https://cheatsheetseries.owasp.org/cheatsheets/Access_Control_Cheat_Sheet.html
-
\ No newline at end of file
+```
+
+
diff --git a/.cursor/rules/python-cryptographic-failures.mdc b/.cursor/rules/python-cryptographic-failures.mdc
index c486193..0113f2f 100644
--- a/.cursor/rules/python-cryptographic-failures.mdc
+++ b/.cursor/rules/python-cryptographic-failures.mdc
@@ -7,7 +7,7 @@ alwaysApply: false
This rule enforces security best practices to prevent cryptographic failures in Python applications, as defined in OWASP Top 10:2021-A02.
-
+```yaml
name: python_cryptographic_failures
description: Detect and prevent cryptographic failures in Python applications as defined in OWASP Top 10:2021-A02
filters:
@@ -22,39 +22,39 @@ actions:
# Pattern 1: Weak or insecure cryptographic algorithms
- pattern: "import\\s+(md5|sha1)|hashlib\\.(md5|sha1)\\(|Crypto\\.Hash\\.(MD5|SHA1)|cryptography\\.hazmat\\.primitives\\.hashes\\.(MD5|SHA1)"
message: "Using weak hashing algorithms (MD5/SHA1). Use SHA-256 or stronger algorithms from the hashlib or cryptography packages."
-
+
# Pattern 2: Hardcoded secrets/credentials
- pattern: "(password|secret|key|token|auth)\\s*=\\s*['\"][^'\"]+['\"]"
message: "Potential hardcoded credentials detected. Store secrets in environment variables or a secure vault."
-
+
# Pattern 3: Insecure random number generation
- pattern: "random\\.(random|randint|choice|sample)|import random"
message: "Using Python's standard random module for security purposes. Use secrets module or cryptography.hazmat.primitives.asymmetric for cryptographic operations."
-
+
# Pattern 4: Weak SSL/TLS configuration
- pattern: "ssl\\.PROTOCOL_(SSLv2|SSLv3|TLSv1|TLSv1_1)|SSLContext\\(\\s*ssl\\.PROTOCOL_(SSLv2|SSLv3|TLSv1|TLSv1_1)\\)"
message: "Using deprecated/insecure SSL/TLS protocol versions. Use TLS 1.2+ (ssl.PROTOCOL_TLS_CLIENT with minimum version set)."
-
+
# Pattern 5: Missing certificate validation
- pattern: "verify\\s*=\\s*False|check_hostname\\s*=\\s*False|CERT_NONE"
message: "SSL certificate validation is disabled. Always validate certificates in production environments."
-
+
# Pattern 6: Insecure cipher usage
- pattern: "DES|RC4|Blowfish|ECB"
message: "Using insecure encryption cipher or mode. Use AES with GCM or CBC mode with proper padding."
-
+
# Pattern 7: Insufficient key length
- pattern: "RSA\\([^,]+,\\s*[0-9]+\\s*\\)|key_size\\s*=\\s*([0-9]|10[0-9][0-9]|11[0-9][0-9]|12[0-4][0-9])"
message: "Using insufficient key length for asymmetric encryption. RSA keys should be at least 2048 bits, preferably 4096 bits."
-
+
# Pattern 8: Insecure password hashing
- pattern: "\\.encode\\(['\"]utf-?8['\"]\\)\\.(digest|hexdigest)\\(\\)|hashlib\\.[a-zA-Z0-9]+\\([^)]*\\)\\.(digest|hexdigest)\\(\\)"
message: "Using plain hashing for passwords. Use dedicated password hashing functions like bcrypt, Argon2, or PBKDF2."
-
+
# Pattern 9: Missing salt in password hashing
- pattern: "pbkdf2_hmac\\([^,]+,[^,]+,[^,]+,\\s*[0-9]+\\s*\\)"
message: "Ensure you're using a proper random salt with password hashing functions."
-
+
# Pattern 10: Insecure cookie settings
- pattern: "set_cookie\\([^)]*secure\\s*=\\s*False|set_cookie\\([^)]*httponly\\s*=\\s*False"
message: "Cookies with sensitive data should have secure and httponly flags enabled."
@@ -62,7 +62,7 @@ actions:
- type: suggest
message: |
**Python Cryptography Best Practices:**
-
+
1. **Secure Password Storage:**
- Use dedicated password hashing algorithms:
```python
@@ -75,7 +75,7 @@ actions:
ph = PasswordHasher()
hash = ph.hash(password)
```
-
+
2. **Secure Random Number Generation:**
- Use the `secrets` module for cryptographic operations:
```python
@@ -87,7 +87,7 @@ actions:
from cryptography.hazmat.primitives.asymmetric import rsa
private_key = rsa.generate_private_key(public_exponent=65537, key_size=4096)
```
-
+
3. **Secure Communications:**
- Use TLS 1.2+ for all communications:
```python
@@ -100,7 +100,7 @@ actions:
import requests
response = requests.get('https://example.com', verify=True)
```
-
+
4. **Proper Key Management:**
- Never hardcode secrets in source code
- Use environment variables or secure vaults:
@@ -109,7 +109,7 @@ actions:
api_key = os.environ.get('API_KEY')
```
- Consider using dedicated key management services
-
+
5. **Secure Encryption:**
- Use high-level libraries like `cryptography`:
```python
@@ -126,7 +126,7 @@ actions:
nonce = os.urandom(12)
encrypted = aesgcm.encrypt(nonce, data, associated_data)
```
-
+
6. **Secure Cookie Handling:**
- Set secure and httponly flags:
```python
@@ -138,7 +138,7 @@ actions:
# Django example - uses signed cookies by default
request.session['user_id'] = user.id
```
-
+
7. **Input Validation:**
- Validate all cryptographic inputs
- Use constant-time comparison for secrets:
@@ -153,15 +153,15 @@ actions:
# Check 1: Proper password hashing
- pattern: "bcrypt\\.hashpw|argon2|PasswordHasher|pbkdf2_hmac\\([^,]+,[^,]+,[^,]+,\\s*[0-9]{4,}\\s*\\)"
message: "Using secure password hashing algorithm."
-
+
# Check 2: Secure random generation
- pattern: "secrets\\.|urandom|cryptography\\.hazmat\\.primitives\\.asymmetric"
message: "Using cryptographically secure random number generation."
-
+
# Check 3: Strong TLS configuration
- pattern: "ssl\\.PROTOCOL_TLS|minimum_version\\s*=\\s*ssl\\.TLSVersion\\.TLSv1_2|create_default_context"
message: "Using secure TLS configuration."
-
+
# Check 4: Proper certificate validation
- pattern: "verify\\s*=\\s*True|check_hostname\\s*=\\s*True|CERT_REQUIRED"
message: "Properly validating SSL certificates."
@@ -190,4 +190,6 @@ metadata:
- "https://cryptography.io/en/latest/"
- "https://pypi.org/project/bcrypt/"
- "https://pypi.org/project/argon2-cffi/"
-
\ No newline at end of file
+```
+
+
diff --git a/.cursor/rules/python-injection.mdc b/.cursor/rules/python-injection.mdc
index 8fc1e95..40cb1d3 100644
--- a/.cursor/rules/python-injection.mdc
+++ b/.cursor/rules/python-injection.mdc
@@ -7,7 +7,7 @@ alwaysApply: false
This rule enforces security best practices to prevent injection vulnerabilities in Python applications, as defined in OWASP Top 10:2021-A03.
-
+```yaml
name: python_injection
description: Detect and prevent injection vulnerabilities in Python applications as defined in OWASP Top 10:2021-A03
filters:
@@ -22,39 +22,39 @@ actions:
# Pattern 1: SQL Injection - String concatenation in SQL queries
- pattern: "cursor\\.(execute|executemany)\\([\"'][^\"']*\\s*[\\+%]|cursor\\.(execute|executemany)\\([^,]+\\+\\s*[a-zA-Z_][a-zA-Z0-9_]*"
message: "Potential SQL injection vulnerability. Use parameterized queries with placeholders instead of string concatenation."
-
+
# Pattern 2: SQL Injection - String formatting in SQL queries
- pattern: "cursor\\.(execute|executemany)\\([\"'][^\"']*%[^\"']*[\"']\\s*%\\s*|cursor\\.(execute|executemany)\\([\"'][^\"']*{[^\"']*}[\"']\\.format"
message: "Potential SQL injection vulnerability. Use parameterized queries with placeholders instead of string formatting."
-
+
# Pattern 3: Command Injection - Shell command execution with user input
- pattern: "(os\\.system|os\\.popen|subprocess\\.Popen|subprocess\\.call|subprocess\\.run|subprocess\\.check_output)\\([^)]*\\+\\s*[a-zA-Z_][a-zA-Z0-9_]*|\\b(os\\.system|os\\.popen|subprocess\\.Popen|subprocess\\.call|subprocess\\.run|subprocess\\.check_output)\\([^)]*format\\(|\\b(os\\.system|os\\.popen|subprocess\\.Popen|subprocess\\.call|subprocess\\.run|subprocess\\.check_output)\\([^)]*f['\"]"
message: "Potential command injection vulnerability. Never use string concatenation or formatting with shell commands. Use subprocess with shell=False and pass arguments as a list."
-
+
# Pattern 4: Command Injection - Shell=True in subprocess
- pattern: "(subprocess\\.Popen|subprocess\\.call|subprocess\\.run|subprocess\\.check_output)\\([^)]*shell\\s*=\\s*True"
message: "Using shell=True with subprocess functions is dangerous and can lead to command injection. Use shell=False (default) and pass arguments as a list."
-
+
# Pattern 5: XSS - Unescaped template variables
- pattern: "\\{\\{\\s*[^|]*\\s*\\}\\}|\\{\\%\\s*autoescape\\s+off\\s*\\%\\}"
message: "Potential XSS vulnerability. Ensure all template variables are properly escaped. Avoid using 'autoescape off' in templates."
-
+
# Pattern 6: XSS - Unsafe HTML rendering in Flask/Django
- pattern: "render_template\\([^)]*\\)|render\\([^)]*\\)|mark_safe\\([^)]*\\)|safe\\s*\\|"
message: "Potential XSS vulnerability. Ensure all user-supplied data is properly escaped before rendering in templates."
-
+
# Pattern 7: Path Traversal - Unsafe file operations
- pattern: "open\\([^)]*\\+|open\\([^)]*format\\(|open\\([^)]*f['\"]"
message: "Potential path traversal vulnerability. Validate and sanitize file paths before opening files. Consider using os.path.abspath and os.path.normpath."
-
+
# Pattern 8: LDAP Injection - Unsafe LDAP queries
- pattern: "ldap\\.search\\([^)]*\\+|ldap\\.search\\([^)]*format\\(|ldap\\.search\\([^)]*f['\"]"
message: "Potential LDAP injection vulnerability. Use proper LDAP escaping for user-supplied input in LDAP queries."
-
+
# Pattern 9: NoSQL Injection - Unsafe MongoDB queries
- pattern: "find\\(\\{[^}]*\\+|find\\(\\{[^}]*format\\(|find\\(\\{[^}]*f['\"]"
message: "Potential NoSQL injection vulnerability. Use parameterized queries or proper escaping for MongoDB queries."
-
+
# Pattern 10: Template Injection - Unsafe template rendering
- pattern: "Template\\([^)]*\\)\\.(render|substitute)\\(|eval\\([^)]*\\)|exec\\([^)]*\\)"
message: "Potential template injection or code injection vulnerability. Avoid using eval() or exec() with user input, and ensure template variables are properly validated."
@@ -62,22 +62,22 @@ actions:
- type: suggest
message: |
**Python Injection Prevention Best Practices:**
-
+
1. **SQL Injection Prevention:**
- Use parameterized queries (prepared statements) with placeholders:
```python
# Safe SQL query with parameters
cursor.execute("SELECT * FROM users WHERE username = %s AND password = %s", (username, password))
-
+
# Django ORM (safe by default)
User.objects.filter(username=username, password=password)
-
+
# SQLAlchemy (safe by default)
session.query(User).filter(User.username == username, User.password == password)
```
- Use ORM frameworks when possible (Django ORM, SQLAlchemy)
- Apply proper input validation and sanitization
-
+
2. **Command Injection Prevention:**
- Never use shell=True with subprocess functions
- Pass command arguments as a list, not a string:
@@ -87,7 +87,7 @@ actions:
```
- Use shlex.quote() if you must include user input in shell commands
- Consider using safer alternatives like Python libraries instead of shell commands
-
+
3. **XSS Prevention:**
- Use template auto-escaping (enabled by default in modern frameworks)
- Explicitly escape user input before rendering:
@@ -95,14 +95,14 @@ actions:
# Django
from django.utils.html import escape
safe_data = escape(user_input)
-
+
# Flask/Jinja2
from markupsafe import escape
safe_data = escape(user_input)
```
- Use Content-Security-Policy headers
- Validate input against allowlists
-
+
4. **Path Traversal Prevention:**
- Validate and sanitize file paths:
```python
@@ -114,7 +114,7 @@ actions:
- Use os.path.abspath() and os.path.normpath()
- Implement proper access controls
- Consider using libraries like Werkzeug's secure_filename()
-
+
5. **NoSQL Injection Prevention:**
- Use parameterized queries or query builders
- Validate input against schemas
@@ -123,7 +123,7 @@ actions:
# Safe MongoDB query
collection.find({"username": username, "status": "active"})
```
-
+
6. **Template Injection Prevention:**
- Avoid using eval() or exec() with user input
- Use sandboxed template engines
@@ -135,15 +135,15 @@ actions:
# Check 1: Safe SQL queries
- pattern: "cursor\\.(execute|executemany)\\([\"'][^\"']*[\"']\\s*,\\s*\\(|cursor\\.(execute|executemany)\\([\"'][^\"']*[\"']\\s*,\\s*\\[|Model\\.objects\\.filter\\(|session\\.query\\("
message: "Using parameterized queries or ORM for database access."
-
+
# Check 2: Safe command execution
- pattern: "(subprocess\\.Popen|subprocess\\.call|subprocess\\.run|subprocess\\.check_output)\\(\\[[^\\]]*\\]"
message: "Using subprocess with arguments as a list (safe pattern)."
-
+
# Check 3: Proper input validation
- pattern: "validate|sanitize|clean|escape|is_valid\\(|validators\\."
message: "Implementing input validation or sanitization."
-
+
# Check 4: Safe file operations
- pattern: "os\\.path\\.join|os\\.path\\.abspath|os\\.path\\.normpath|secure_filename"
message: "Using safe file path handling techniques."
@@ -175,4 +175,5 @@ metadata:
- "https://docs.python.org/3/library/subprocess.html"
- "https://docs.djangoproject.com/en/stable/topics/security/"
- "https://flask.palletsprojects.com/en/latest/security/"
-
\ No newline at end of file
+```
+
diff --git a/.cursor/rules/python-insecure-design.mdc b/.cursor/rules/python-insecure-design.mdc
index c7fa352..25cb177 100644
--- a/.cursor/rules/python-insecure-design.mdc
+++ b/.cursor/rules/python-insecure-design.mdc
@@ -7,7 +7,7 @@ alwaysApply: false
This rule enforces security best practices to prevent insecure design vulnerabilities in Python applications, as defined in OWASP Top 10:2021-A04.
-
+```yaml
name: python_insecure_design
description: Detect and prevent insecure design patterns in Python applications as defined in OWASP Top 10:2021-A04
filters:
@@ -22,39 +22,39 @@ actions:
# Pattern 1: Lack of input validation
- pattern: "def\\s+[a-zA-Z0-9_]+\\([^)]*\\):\\s*(?![^#]*validate|[^#]*clean|[^#]*sanitize|[^#]*check|[^#]*is_valid)"
message: "Function lacks input validation. Consider implementing validation for all user-supplied inputs."
-
+
# Pattern 2: Hardcoded business rules
- pattern: "if\\s+[a-zA-Z0-9_]+\\s*(==|!=|>|<|>=|<=)\\s*['\"][^'\"]+['\"]:"
message: "Hardcoded business rules detected. Consider using configuration files or database-driven rules for better maintainability."
-
+
# Pattern 3: Lack of rate limiting
- pattern: "@(app|api|route|blueprint)\\.(get|post|put|delete|patch)\\([^)]*\\)\\s*\\n\\s*(?![^#]*rate_limit|[^#]*throttle|[^#]*limiter)"
message: "API endpoint lacks rate limiting. Consider implementing rate limiting to prevent abuse."
-
+
# Pattern 4: Insecure default configurations
- pattern: "DEBUG\\s*=\\s*True|DEVELOPMENT\\s*=\\s*True|TESTING\\s*=\\s*True"
message: "Insecure default configuration detected. Ensure debug/development modes are disabled in production."
-
+
# Pattern 5: Lack of error handling
- pattern: "(?
\ No newline at end of file
+```
+
diff --git a/.cursor/rules/python-integrity-failures.mdc b/.cursor/rules/python-integrity-failures.mdc
index 8294d12..162ee66 100644
--- a/.cursor/rules/python-integrity-failures.mdc
+++ b/.cursor/rules/python-integrity-failures.mdc
@@ -7,7 +7,7 @@ alwaysApply: false
This rule enforces security best practices to prevent software and data integrity failures in Python applications, as defined in OWASP Top 10:2021-A08.
-
+```yaml
name: python_integrity_failures
description: Detect and prevent software and data integrity failures in Python applications as defined in OWASP Top 10:2021-A08
filters:
@@ -22,59 +22,59 @@ actions:
# Pattern 1: Insecure deserialization with pickle
- pattern: "pickle\\.loads\\(|pickle\\.load\\(|cPickle\\.loads\\(|cPickle\\.load\\("
message: "Insecure deserialization detected with pickle. Pickle is not secure against maliciously constructed data and should not be used with untrusted input."
-
+
# Pattern 2: Insecure deserialization with yaml.load
- pattern: "yaml\\.load\\([^,)]+\\)|yaml\\.load\\([^,)]+,\\s*Loader=yaml\\.Loader\\)"
message: "Insecure deserialization detected with yaml.load(). Use yaml.safe_load() instead for untrusted input."
-
+
# Pattern 3: Insecure deserialization with marshal
- pattern: "marshal\\.loads\\(|marshal\\.load\\("
message: "Insecure deserialization detected with marshal. Marshal is not secure against maliciously constructed data."
-
+
# Pattern 4: Insecure deserialization with shelve
- pattern: "shelve\\.open\\("
message: "Potentially insecure deserialization with shelve detected. Shelve uses pickle internally and is not secure against malicious data."
-
+
# Pattern 5: Insecure use of eval or exec
- pattern: "eval\\(|exec\\(|compile\\([^,]+,\\s*['\"][^'\"]+['\"]\\s*,\\s*['\"]exec['\"]\\)"
message: "Insecure use of eval() or exec() detected. These functions can execute arbitrary code and should never be used with untrusted input."
-
+
# Pattern 6: Missing integrity verification for downloads
- pattern: "urllib\\.request\\.urlretrieve\\(|requests\\.get\\([^)]*\\.exe['\"]\\)|requests\\.get\\([^)]*\\.zip['\"]\\)|requests\\.get\\([^)]*\\.tar\\.gz['\"]\\)"
message: "File download without integrity verification detected. Always verify the integrity of downloaded files using checksums or digital signatures."
-
+
# Pattern 7: Insecure package installation
- pattern: "pip\\s+install\\s+[^-]|subprocess\\.(?:call|run|Popen)\\(['\"]pip\\s+install"
message: "Insecure package installation detected. Specify package versions and consider using hash verification for pip installations."
-
+
# Pattern 8: Missing integrity checks for configuration
- pattern: "config\\.read\\(|json\\.loads?\\(|yaml\\.safe_load\\(|toml\\.loads?\\("
message: "Configuration loading detected. Ensure integrity verification for configuration files, especially in production environments."
-
+
# Pattern 9: Insecure temporary file creation
- pattern: "tempfile\\.mktemp\\(|os\\.tempnam\\(|os\\.tmpnam\\("
message: "Insecure temporary file creation detected. Use tempfile.mkstemp() or tempfile.TemporaryFile() instead to avoid race conditions."
-
+
# Pattern 10: Insecure file operations with untrusted paths
- pattern: "open\\([^,)]+\\+\\s*request\\.|open\\([^,)]+\\+\\s*user_|open\\([^,)]+\\+\\s*input\\("
message: "Potentially insecure file operation with user-controlled path detected. Validate and sanitize file paths from untrusted sources."
-
+
# Pattern 11: Missing integrity checks for updates
- pattern: "auto_update|self_update|check_for_updates"
message: "Update mechanism detected. Ensure proper integrity verification for software updates using digital signatures or secure checksums."
-
+
# Pattern 12: Insecure plugin or extension loading
- pattern: "importlib\\.import_module\\(|__import__\\(|load_plugin|load_extension|load_module"
message: "Dynamic module loading detected. Implement integrity checks and validation before loading external modules or plugins."
-
+
# Pattern 13: Insecure use of subprocess with shell=True
- pattern: "subprocess\\.(?:call|run|Popen)\\([^,)]*shell\\s*=\\s*True"
message: "Insecure subprocess execution with shell=True detected. This can lead to command injection if user input is involved."
-
+
# Pattern 14: Missing integrity verification for serialized data
- pattern: "json\\.loads?\\([^,)]*request\\.|json\\.loads?\\([^,)]*user_|json\\.loads?\\([^,)]*input\\("
message: "Deserialization of user-controlled data detected. Implement schema validation or integrity checks before processing."
-
+
# Pattern 15: Insecure use of globals or locals
- pattern: "globals\\(\\)\\[|locals\\(\\)\\["
message: "Potentially insecure modification of globals or locals detected. This can lead to unexpected behavior or security issues."
@@ -82,7 +82,7 @@ actions:
- type: suggest
message: |
**Python Software and Data Integrity Best Practices:**
-
+
1. **Secure Deserialization:**
- Avoid using pickle, marshal, or shelve with untrusted data
- Use safer alternatives like JSON with schema validation
@@ -90,7 +90,7 @@ actions:
```python
import json
import jsonschema
-
+
# Define a schema for validation
schema = {
"type": "object",
@@ -100,7 +100,7 @@ actions:
},
"required": ["name", "age"]
}
-
+
# Validate data against schema
try:
data = json.loads(user_input)
@@ -110,41 +110,41 @@ actions:
# Handle validation error
print(f"Invalid data: {e}")
```
-
+
2. **YAML Safe Loading:**
- Always use yaml.safe_load() instead of yaml.load()
- Example:
```python
import yaml
-
+
# Safe way to load YAML
data = yaml.safe_load(yaml_string)
-
+
# Avoid this:
# data = yaml.load(yaml_string) # Insecure!
```
-
+
3. **Integrity Verification for Downloads:**
- Verify checksums or signatures for downloaded files
- Example:
```python
import hashlib
import requests
-
+
def download_with_integrity_check(url, expected_hash):
response = requests.get(url)
file_data = response.content
-
+
# Calculate hash
calculated_hash = hashlib.sha256(file_data).hexdigest()
-
+
# Verify integrity
if calculated_hash != expected_hash:
raise ValueError("Integrity check failed: hash mismatch")
-
+
return file_data
```
-
+
4. **Secure Package Installation:**
- Pin dependencies to specific versions
- Use hash verification for pip installations
@@ -153,7 +153,7 @@ actions:
# requirements.txt
requests==2.31.0 --hash=sha256:942c5a758f98d790eaed1a29cb6eefc7ffb0d1cf7af05c3d2791656dbd6ad1e1
```
-
+
5. **Secure Configuration Management:**
- Validate configuration file integrity
- Use environment-specific configurations
@@ -162,34 +162,34 @@ actions:
import json
import hmac
import hashlib
-
+
def load_config_with_integrity(config_file, secret_key):
with open(config_file, 'r') as f:
content = f.read()
-
+
# Split content into data and signature
data, _, signature = content.rpartition('\n')
-
+
# Verify integrity
expected_signature = hmac.new(
- secret_key.encode(),
- data.encode(),
+ secret_key.encode(),
+ data.encode(),
hashlib.sha256
).hexdigest()
-
+
if not hmac.compare_digest(signature, expected_signature):
raise ValueError("Configuration integrity check failed")
-
+
return json.loads(data)
```
-
+
6. **Secure Temporary Files:**
- Use secure temporary file functions
- Example:
```python
import tempfile
import os
-
+
# Secure temporary file creation
fd, temp_path = tempfile.mkstemp()
try:
@@ -198,14 +198,14 @@ actions:
# Process the file
finally:
os.unlink(temp_path) # Clean up
-
+
# Or use context manager
with tempfile.TemporaryFile() as temp_file:
temp_file.write(b'data')
temp_file.seek(0)
# Process the file
```
-
+
7. **Secure Update Mechanisms:**
- Verify signatures for updates
- Use HTTPS for update downloads
@@ -213,23 +213,23 @@ actions:
```python
import requests
import gnupg
-
+
def secure_update(update_url, signature_url, gpg_key):
# Download update and signature
update_data = requests.get(update_url).content
signature = requests.get(signature_url).content
-
+
# Verify signature
gpg = gnupg.GPG()
gpg.import_keys(gpg_key)
verified = gpg.verify_data(signature, update_data)
-
+
if not verified:
raise ValueError("Update signature verification failed")
-
+
return update_data
```
-
+
8. **Secure Plugin Loading:**
- Validate plugins before loading
- Implement allowlisting for plugins
@@ -237,30 +237,30 @@ actions:
```python
import importlib
import hashlib
-
+
# Allowlist of approved plugins with their hashes
APPROVED_PLUGINS = {
'safe_plugin': 'sha256:1234567890abcdef',
'other_plugin': 'sha256:abcdef1234567890'
}
-
+
def load_plugin_safely(plugin_name, plugin_path):
# Check if plugin is in allowlist
if plugin_name not in APPROVED_PLUGINS:
raise ValueError(f"Plugin {plugin_name} is not approved")
-
+
# Calculate plugin file hash
with open(plugin_path, 'rb') as f:
plugin_hash = 'sha256:' + hashlib.sha256(f.read()).hexdigest()
-
+
# Verify hash matches expected value
if plugin_hash != APPROVED_PLUGINS[plugin_name]:
raise ValueError(f"Plugin {plugin_name} failed integrity check")
-
+
# Load plugin safely
return importlib.import_module(plugin_name)
```
-
+
9. **Secure Subprocess Execution:**
- Avoid shell=True
- Use allowlists for commands
@@ -268,44 +268,44 @@ actions:
```python
import subprocess
import shlex
-
+
def run_command_safely(command, arguments):
# Allowlist of safe commands
SAFE_COMMANDS = {'ls', 'echo', 'cat'}
-
+
if command not in SAFE_COMMANDS:
raise ValueError(f"Command {command} is not allowed")
-
+
# Build command with arguments
cmd = [command] + arguments
-
+
# Execute without shell
return subprocess.run(cmd, shell=False, capture_output=True, text=True)
```
-
+
10. **Input Validation and Sanitization:**
- Validate all inputs before processing
- Use schema validation for structured data
- Example with Pydantic:
```python
from pydantic import BaseModel, validator
-
+
class UserData(BaseModel):
username: str
age: int
-
+
@validator('username')
def username_must_be_valid(cls, v):
if not v.isalnum() or len(v) > 30:
raise ValueError('Username must be alphanumeric and <= 30 chars')
return v
-
+
@validator('age')
def age_must_be_reasonable(cls, v):
if v < 0 or v > 120:
raise ValueError('Age must be between 0 and 120')
return v
-
+
# Usage
try:
user = UserData(username=user_input_name, age=user_input_age)
@@ -320,15 +320,15 @@ actions:
# Check 1: Safe YAML loading
- pattern: "yaml\\.safe_load\\("
message: "Using safe YAML loading."
-
+
# Check 2: Secure temporary file usage
- pattern: "tempfile\\.mkstemp\\(|tempfile\\.TemporaryFile\\(|tempfile\\.NamedTemporaryFile\\("
message: "Using secure temporary file functions."
-
+
# Check 3: Secure subprocess usage
- pattern: "subprocess\\.(?:call|run|Popen)\\([^,)]*shell\\s*=\\s*False"
message: "Using subprocess with shell=False."
-
+
# Check 4: Input validation
- pattern: "jsonschema\\.validate|pydantic|dataclass|@validator"
message: "Implementing input validation."
@@ -358,4 +358,6 @@ metadata:
- "https://pyyaml.org/wiki/PyYAMLDocumentation"
- "https://python-security.readthedocs.io/packages.html"
- "https://docs.python.org/3/library/tempfile.html#security"
-
\ No newline at end of file
+```
+
+
diff --git a/.cursor/rules/python-logging-monitoring-failures.mdc b/.cursor/rules/python-logging-monitoring-failures.mdc
index e9f1118..c559044 100644
--- a/.cursor/rules/python-logging-monitoring-failures.mdc
+++ b/.cursor/rules/python-logging-monitoring-failures.mdc
@@ -7,7 +7,7 @@ alwaysApply: false
This rule enforces security best practices to prevent security logging and monitoring failures in Python applications, as defined in OWASP Top 10:2021-A09.
-
+```yaml
name: python_logging_monitoring_failures
description: Detect and prevent security logging and monitoring failures in Python applications as defined in OWASP Top 10:2021-A09
filters:
@@ -22,59 +22,59 @@ actions:
# Pattern 1: Missing logging in authentication functions
- pattern: "def\\s+(login|authenticate|signin|logout|signout).*?:[^\\n]*?(?!.*logging\\.(info|warning|error|critical))"
message: "Authentication function without logging detected. Always log authentication events, especially failures, for security monitoring."
-
+
# Pattern 2: Missing logging in authorization functions
- pattern: "def\\s+(authorize|check_permission|has_permission|is_authorized|require_permission).*?:[^\\n]*?(?!.*logging\\.(info|warning|error|critical))"
message: "Authorization function without logging detected. Always log authorization decisions, especially denials, for security monitoring."
-
+
# Pattern 3: Missing logging in security-sensitive operations
- pattern: "def\\s+(create_user|update_user|delete_user|reset_password|change_password).*?:[^\\n]*?(?!.*logging\\.(info|warning|error|critical))"
message: "Security-sensitive user operation without logging detected. Always log security-sensitive operations for audit trails."
-
+
# Pattern 4: Missing logging in exception handlers
- pattern: "except\\s+[^:]+:[^\\n]*?(?!.*logging\\.(warning|error|critical|exception))"
message: "Exception handler without logging detected. Always log exceptions, especially in security-sensitive code, for monitoring and debugging."
-
+
# Pattern 5: Logging sensitive data
- pattern: "logging\\.(debug|info|warning|error|critical)\\([^)]*?(password|token|secret|key|credential|auth)"
message: "Potential sensitive data logging detected. Avoid logging sensitive information like passwords, tokens, or keys."
-
+
# Pattern 6: Insufficient log level in security context
- pattern: "logging\\.debug\\([^)]*?(auth|login|permission|security|attack|hack|exploit|vulnerability)"
message: "Debug-level logging for security events detected. Use appropriate log levels (INFO, WARNING, ERROR) for security events."
-
+
# Pattern 7: Missing logging configuration
- pattern: "import\\s+logging(?!.*logging\\.basicConfig|.*logging\\.config)"
message: "Logging import without configuration detected. Configure logging properly with appropriate handlers, formatters, and levels."
-
+
# Pattern 8: Insecure logging configuration
- pattern: "logging\\.basicConfig\\([^)]*?level\\s*=\\s*logging\\.DEBUG"
message: "Debug-level logging configuration detected. Use appropriate log levels in production to avoid excessive logging."
-
+
# Pattern 9: Missing request/response logging in web frameworks
- pattern: "@app\\.route\\(['\"][^'\"]+['\"]|@api_view\\(|class\\s+\\w+\\(APIView\\)|class\\s+\\w+\\(View\\)"
message: "Web endpoint without request logging detected. Consider logging requests and responses for security monitoring."
-
+
# Pattern 10: Missing correlation IDs in logs
- pattern: "logging\\.(debug|info|warning|error|critical)\\([^)]*?(?!.*request_id|.*correlation_id|.*trace_id)"
message: "Logging without correlation ID detected. Include correlation IDs in logs to trace requests across systems."
-
+
# Pattern 11: Missing error handling for logging failures
- pattern: "logging\\.(debug|info|warning|error|critical)\\([^)]*?\\)"
message: "Logging without error handling detected. Handle potential logging failures to ensure critical events are not missed."
-
+
# Pattern 12: Missing logging for database operations
- pattern: "(execute|executemany|cursor\\.execute|session\\.execute|query)\\([^)]*?(?!.*logging\\.(debug|info|warning|error|critical))"
message: "Database operation without logging detected. Consider logging database operations for audit trails and security monitoring."
-
+
# Pattern 13: Missing logging for file operations
- pattern: "open\\([^)]+,\\s*['\"]w['\"]|open\\([^)]+,\\s*['\"]a['\"]|write\\(|writelines\\("
message: "File write operation without logging detected. Consider logging file operations for audit trails."
-
+
# Pattern 14: Missing logging for subprocess execution
- pattern: "subprocess\\.(call|run|Popen)\\([^)]*?(?!.*logging\\.(debug|info|warning|error|critical))"
message: "Subprocess execution without logging detected. Always log command execution for security monitoring."
-
+
# Pattern 15: Missing centralized logging configuration
- pattern: "logging\\.basicConfig\\([^)]*?(?!.*filename|.*handlers)"
message: "Console-only logging configuration detected. Configure centralized logging with file handlers or external logging services."
@@ -82,7 +82,7 @@ actions:
- type: suggest
message: |
**Python Security Logging and Monitoring Best Practices:**
-
+
1. **Structured Logging:**
- Use structured logging formats (JSON)
- Include contextual information
@@ -90,7 +90,7 @@ actions:
```python
import logging
import json
-
+
class JsonFormatter(logging.Formatter):
def format(self, record):
log_record = {
@@ -101,25 +101,25 @@ actions:
"path": record.pathname,
"line": record.lineno
}
-
+
# Add extra attributes from record
for key, value in record.__dict__.items():
- if key not in ["args", "asctime", "created", "exc_info", "exc_text",
+ if key not in ["args", "asctime", "created", "exc_info", "exc_text",
"filename", "funcName", "id", "levelname", "levelno",
- "lineno", "module", "msecs", "message", "msg", "name",
- "pathname", "process", "processName", "relativeCreated",
+ "lineno", "module", "msecs", "message", "msg", "name",
+ "pathname", "process", "processName", "relativeCreated",
"stack_info", "thread", "threadName"]:
log_record[key] = value
-
+
return json.dumps(log_record)
-
+
# Configure logger with JSON formatter
logger = logging.getLogger("security_logger")
handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter())
logger.addHandler(handler)
logger.setLevel(logging.INFO)
-
+
# Usage with context
logger.info("User login successful", extra={
"user_id": user.id,
@@ -127,7 +127,7 @@ actions:
"request_id": request.headers.get("X-Request-ID")
})
```
-
+
2. **Security Event Logging:**
- Log all authentication events
- Log authorization decisions
@@ -137,7 +137,7 @@ actions:
def login(request):
username = request.form.get("username")
password = request.form.get("password")
-
+
try:
user = authenticate(username, password)
if user:
@@ -166,7 +166,7 @@ actions:
})
return error_response("Login error")
```
-
+
3. **Correlation IDs:**
- Use request IDs to correlate logs
- Propagate IDs across services
@@ -174,28 +174,28 @@ actions:
```python
import uuid
from flask import Flask, request, g
-
+
app = Flask(__name__)
-
+
@app.before_request
def before_request():
request_id = request.headers.get("X-Request-ID")
if not request_id:
request_id = str(uuid.uuid4())
g.request_id = request_id
-
+
@app.after_request
def after_request(response):
response.headers["X-Request-ID"] = g.request_id
return response
-
+
# In your view functions
@app.route("/api/resource")
def get_resource():
logger.info("Resource accessed", extra={"request_id": g.request_id})
return jsonify({"data": "resource"})
```
-
+
4. **Appropriate Log Levels:**
- DEBUG: Detailed information for debugging
- INFO: Confirmation of normal events
@@ -206,28 +206,28 @@ actions:
```python
# Normal operation
logger.info("User profile updated", extra={"user_id": user.id})
-
+
# Potential security issue
logger.warning("Multiple failed login attempts", extra={
"username": username,
"attempt_count": attempts,
"ip_address": ip_address
})
-
+
# Security violation
logger.error("Unauthorized access attempt", extra={
"user_id": user.id,
"resource": resource_id,
"ip_address": ip_address
})
-
+
# Critical security breach
logger.critical("Possible data breach detected", extra={
"indicators": indicators,
"affected_resources": resources
})
```
-
+
5. **Centralized Logging:**
- Configure logging to centralized systems
- Use appropriate handlers
@@ -235,9 +235,9 @@ actions:
```python
import logging
from logging.handlers import RotatingFileHandler
-
+
logger = logging.getLogger("security_logger")
-
+
# File handler with rotation
file_handler = RotatingFileHandler(
"security.log",
@@ -246,11 +246,11 @@ actions:
)
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger.addHandler(file_handler)
-
+
# Set level
logger.setLevel(logging.INFO)
```
-
+
6. **Sensitive Data Handling:**
- Never log sensitive data
- Implement data masking
@@ -263,13 +263,13 @@ actions:
if field in masked_data:
masked_data[field] = "********"
return masked_data
-
+
# Usage
user_data = {"username": "john", "password": "secret123", "email": "john@example.com"}
safe_data = mask_sensitive_data(user_data, ["password"])
logger.info("User data processed", extra={"user_data": safe_data})
```
-
+
7. **Exception Logging:**
- Always log exceptions
- Include stack traces for debugging
@@ -289,7 +289,7 @@ actions:
)
raise # Re-raise or handle appropriately
```
-
+
8. **Audit Logging:**
- Log all security-relevant changes
- Include before/after states
@@ -298,11 +298,11 @@ actions:
def update_user_role(user_id, new_role, current_user):
user = User.get(user_id)
old_role = user.role
-
+
# Update role
user.role = new_role
user.save()
-
+
# Audit log
logger.info("User role changed", extra={
"user_id": user_id,
@@ -312,7 +312,7 @@ actions:
"timestamp": datetime.utcnow().isoformat()
})
```
-
+
9. **Log Monitoring Integration:**
- Configure alerts for security events
- Integrate with SIEM systems
@@ -321,14 +321,14 @@ actions:
import logging
from elasticsearch import Elasticsearch
from elasticsearch.helpers import bulk
-
+
class ElasticsearchHandler(logging.Handler):
def __init__(self, es_host, index_name):
super().__init__()
self.es = Elasticsearch([es_host])
self.index_name = index_name
self.buffer = []
-
+
def emit(self, record):
try:
log_entry = {
@@ -340,35 +340,35 @@ actions:
"logger": record.name
}
}
-
+
# Add extra fields
for key, value in record.__dict__.items():
- if key not in ["args", "asctime", "created", "exc_info", "exc_text",
+ if key not in ["args", "asctime", "created", "exc_info", "exc_text",
"filename", "funcName", "id", "levelname", "levelno",
- "lineno", "module", "msecs", "message", "msg", "name",
- "pathname", "process", "processName", "relativeCreated",
+ "lineno", "module", "msecs", "message", "msg", "name",
+ "pathname", "process", "processName", "relativeCreated",
"stack_info", "thread", "threadName"]:
log_entry["_source"][key] = value
-
+
self.buffer.append(log_entry)
-
+
# Bulk insert if buffer is full
if len(self.buffer) >= 10:
self.flush()
except Exception:
self.handleError(record)
-
+
def flush(self):
if self.buffer:
bulk(self.es, self.buffer)
self.buffer = []
-
+
# Usage
es_handler = ElasticsearchHandler("localhost:9200", "app-logs")
es_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger.addHandler(es_handler)
```
-
+
10. **Logging Failure Handling:**
- Handle logging failures gracefully
- Implement fallback mechanisms
@@ -379,7 +379,7 @@ actions:
super().__init__()
self.primary_handler = primary_handler
self.fallback_handler = fallback_handler
-
+
def emit(self, record):
try:
self.primary_handler.emit(record)
@@ -390,7 +390,7 @@ actions:
# Last resort: print to stderr
import sys
print(f"CRITICAL: Logging failure: {record.getMessage()}", file=sys.stderr)
-
+
# Usage
primary = ElasticsearchHandler("localhost:9200", "app-logs")
fallback = logging.FileHandler("fallback.log")
@@ -403,15 +403,15 @@ actions:
# Check 1: Proper logging configuration
- pattern: "logging\\.basicConfig\\(|logging\\.config\\.dictConfig\\(|logging\\.config\\.fileConfig\\("
message: "Logging is properly configured."
-
+
# Check 2: Security event logging
- pattern: "logging\\.(info|warning|error|critical)\\([^)]*?(login|authenticate|authorize|permission)"
message: "Security events are being logged."
-
+
# Check 3: Structured logging
- pattern: "logging\\.(info|warning|error|critical)\\([^)]*?extra\\s*="
message: "Structured logging with context is implemented."
-
+
# Check 4: Correlation ID usage
- pattern: "request_id|correlation_id|trace_id"
message: "Correlation IDs are used for request tracing."
@@ -441,4 +441,5 @@ metadata:
- "https://docs.djangoproject.com/en/stable/topics/logging/"
- "https://flask.palletsprojects.com/en/latest/logging/"
- "https://fastapi.tiangolo.com/tutorial/handling-errors/#logging"
-
\ No newline at end of file
+```
+
diff --git a/.cursor/rules/python-security-misconfiguration.mdc b/.cursor/rules/python-security-misconfiguration.mdc
index 5e9a2a2..fafc438 100644
--- a/.cursor/rules/python-security-misconfiguration.mdc
+++ b/.cursor/rules/python-security-misconfiguration.mdc
@@ -7,7 +7,7 @@ alwaysApply: false
This rule enforces security best practices to prevent security misconfigurations in Python applications, as defined in OWASP Top 10:2021-A05.
-
+```yaml
name: python_security_misconfiguration
description: Detect and prevent security misconfigurations in Python applications as defined in OWASP Top 10:2021-A05
filters:
@@ -22,59 +22,59 @@ actions:
# Pattern 1: Debug mode enabled in production settings
- pattern: "DEBUG\\s*=\\s*True|debug\\s*=\\s*true|\"debug\"\\s*:\\s*true|debug:\\s*true"
message: "Debug mode appears to be enabled. This should be disabled in production environments as it can expose sensitive information."
-
+
# Pattern 2: Insecure cookie settings
- pattern: "SESSION_COOKIE_SECURE\\s*=\\s*False|session_cookie_secure\\s*=\\s*false|\"session_cookie_secure\"\\s*:\\s*false|session_cookie_secure:\\s*false"
message: "Insecure cookie configuration detected. Set SESSION_COOKIE_SECURE to True in production environments."
-
+
# Pattern 3: Missing CSRF protection
- pattern: "CSRF_ENABLED\\s*=\\s*False|csrf_enabled\\s*=\\s*false|\"csrf_enabled\"\\s*:\\s*false|csrf_enabled:\\s*false|WTF_CSRF_ENABLED\\s*=\\s*False"
message: "CSRF protection appears to be disabled. Enable CSRF protection to prevent cross-site request forgery attacks."
-
+
# Pattern 4: Insecure CORS settings
- pattern: "CORS_ORIGIN_ALLOW_ALL\\s*=\\s*True|cors_origin_allow_all\\s*=\\s*true|\"cors_origin_allow_all\"\\s*:\\s*true|cors_origin_allow_all:\\s*true|Access-Control-Allow-Origin:\\s*\\*"
message: "Overly permissive CORS configuration detected. Restrict CORS to specific origins rather than allowing all origins."
-
+
# Pattern 5: Default or weak secret keys
- pattern: "SECRET_KEY\\s*=\\s*['\"]default|SECRET_KEY\\s*=\\s*['\"][a-zA-Z0-9]{1,32}['\"]|secret_key\\s*=\\s*['\"]default|\"secret_key\"\\s*:\\s*\"default|secret_key:\\s*default"
message: "Default or potentially weak secret key detected. Use a strong, randomly generated secret key and store it securely."
-
+
# Pattern 6: Exposed sensitive information in error messages
- pattern: "DEBUG_PROPAGATE_EXCEPTIONS\\s*=\\s*True|debug_propagate_exceptions\\s*=\\s*true|\"debug_propagate_exceptions\"\\s*:\\s*true|debug_propagate_exceptions:\\s*true"
message: "Exception propagation in debug mode is enabled. This can expose sensitive information in error messages."
-
+
# Pattern 7: Insecure SSL/TLS configuration
- pattern: "SECURE_SSL_REDIRECT\\s*=\\s*False|secure_ssl_redirect\\s*=\\s*false|\"secure_ssl_redirect\"\\s*:\\s*false|secure_ssl_redirect:\\s*false"
message: "SSL redirection appears to be disabled. Enable SSL redirection to ensure secure communications."
-
+
# Pattern 8: Missing security headers
- pattern: "SECURE_HSTS_SECONDS\\s*=\\s*0|secure_hsts_seconds\\s*=\\s*0|\"secure_hsts_seconds\"\\s*:\\s*0|secure_hsts_seconds:\\s*0"
message: "HTTP Strict Transport Security (HSTS) appears to be disabled. Enable HSTS to enforce secure communications."
-
+
# Pattern 9: Exposed sensitive directories
- pattern: "@app\\.route\\(['\"]/(admin|console|management|config|settings|system)['\"]"
message: "Potentially sensitive endpoint exposed without access controls. Ensure proper authentication and authorization for administrative endpoints."
-
+
# Pattern 10: Default accounts or credentials
- pattern: "username\\s*=\\s*['\"]admin['\"]|password\\s*=\\s*['\"]admin|password\\s*=\\s*['\"]password|password\\s*=\\s*['\"]123|user\\s*=\\s*['\"]root['\"]"
message: "Default or weak credentials detected. Never use default or easily guessable credentials in any environment."
-
+
# Pattern 11: Insecure file permissions
- pattern: "os\\.chmod\\([^,]+,\\s*0o777\\)|os\\.chmod\\([^,]+,\\s*777\\)"
message: "Overly permissive file permissions detected. Use the principle of least privilege for file permissions."
-
+
# Pattern 12: Exposed version information
- pattern: "@app\\.route\\(['\"]/(version|build|status|health)['\"]"
message: "Endpoints that may expose version information detected. Ensure these endpoints don't reveal sensitive details about your application."
-
+
# Pattern 13: Insecure deserialization
- pattern: "pickle\\.loads|yaml\\.load\\([^,)]+\\)|json\\.loads\\([^,)]+,\\s*[^)]*object_hook"
message: "Potentially insecure deserialization detected. Use safer alternatives like yaml.safe_load() or validate input before deserialization."
-
+
# Pattern 14: Missing timeout settings
- pattern: "requests\\.get\\([^,)]+\\)|requests\\.(post|put|delete|patch)\\([^,)]+\\)"
message: "HTTP request without timeout setting detected. Always set timeouts for HTTP requests to prevent denial of service."
-
+
# Pattern 15: Insecure upload directory
- pattern: "UPLOAD_FOLDER\\s*=\\s*['\"][^'\"]*(/tmp|/var/tmp)[^'\"]*['\"]|upload_folder\\s*=\\s*['\"][^'\"]*(/tmp|/var/tmp)[^'\"]*['\"]"
message: "Insecure upload directory detected. Use a properly secured directory for file uploads, not temporary directories."
@@ -82,18 +82,18 @@ actions:
- type: suggest
message: |
**Python Security Configuration Best Practices:**
-
+
1. **Environment-Specific Configuration:**
- Use different configurations for development, testing, and production
- Never enable debug mode in production
- Example with environment variables:
```python
import os
-
+
DEBUG = os.environ.get('DEBUG', 'False') == 'True'
SECRET_KEY = os.environ.get('SECRET_KEY')
```
-
+
2. **Secure Cookie Configuration:**
- Enable secure cookies in production
- Set appropriate cookie flags
@@ -114,13 +114,13 @@ actions:
PERMANENT_SESSION_LIFETIME=timedelta(hours=1)
)
```
-
+
3. **Security Headers:**
- Implement HTTP security headers
- Example with Flask-Talisman:
```python
from flask_talisman import Talisman
-
+
talisman = Talisman(
app,
content_security_policy={
@@ -141,13 +141,13 @@ actions:
SECURE_BROWSER_XSS_FILTER = True
X_FRAME_OPTIONS = 'DENY'
```
-
+
4. **CORS Configuration:**
- Restrict CORS to specific origins
- Example with Flask-CORS:
```python
from flask_cors import CORS
-
+
CORS(app, resources={r"/api/*": {"origins": "https://example.com"}})
```
- Example for Django:
@@ -158,18 +158,18 @@ actions:
]
CORS_ALLOW_CREDENTIALS = True
```
-
+
5. **Secret Management:**
- Use environment variables or secure vaults for secrets
- Generate strong random secrets
- Example:
```python
import secrets
-
+
# Generate a secure random secret key
secret_key = secrets.token_hex(32)
```
-
+
6. **Error Handling:**
- Use custom error handlers to prevent information leakage
- Example for Flask:
@@ -181,7 +181,7 @@ actions:
# Return a generic error message
return jsonify({"error": "An unexpected error occurred"}), 500
```
-
+
7. **Secure File Uploads:**
- Validate file types and sizes
- Store uploaded files outside the web root
@@ -190,17 +190,17 @@ actions:
```python
import os
from werkzeug.utils import secure_filename
-
+
UPLOAD_FOLDER = '/path/to/secure/location'
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg'}
-
+
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB limit
-
+
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
```
-
+
8. **Dependency Management:**
- Regularly update dependencies
- Use tools like safety or dependabot
@@ -210,23 +210,23 @@ actions:
Flask==2.0.1
Werkzeug==2.0.1
```
-
+
9. **Timeout Configuration:**
- Set timeouts for all external service calls
- Example:
```python
import requests
-
+
response = requests.get('https://api.example.com', timeout=(3.05, 27))
```
-
+
10. **Secure Deserialization:**
- Use safe alternatives for deserialization
- Validate input before deserialization
- Example:
```python
import yaml
-
+
# Use safe_load instead of load
data = yaml.safe_load(yaml_string)
```
@@ -236,15 +236,15 @@ actions:
# Check 1: Proper debug configuration
- pattern: "DEBUG\\s*=\\s*os\\.environ\\.get\\(['\"]DEBUG['\"]|DEBUG\\s*=\\s*False"
message: "Using environment-specific or secure debug configuration."
-
+
# Check 2: Secure cookie settings
- pattern: "SESSION_COOKIE_SECURE\\s*=\\s*True|session_cookie_secure\\s*=\\s*true"
message: "Using secure cookie configuration."
-
+
# Check 3: Security headers implementation
- pattern: "SECURE_HSTS_SECONDS|X_FRAME_OPTIONS|Talisman\\(|CSP|Content-Security-Policy"
message: "Implementing security headers."
-
+
# Check 4: Proper CORS configuration
- pattern: "CORS_ALLOWED_ORIGINS|CORS\\(app,\\s*resources"
message: "Using restricted CORS configuration."
@@ -273,4 +273,5 @@ metadata:
- "https://docs.djangoproject.com/en/stable/topics/security/"
- "https://fastapi.tiangolo.com/advanced/security/https/"
- "https://owasp.org/www-project-secure-headers/"
-
\ No newline at end of file
+```
+
diff --git a/.cursor/rules/python-ssrf.mdc b/.cursor/rules/python-ssrf.mdc
index a8bba07..9e0e498 100644
--- a/.cursor/rules/python-ssrf.mdc
+++ b/.cursor/rules/python-ssrf.mdc
@@ -7,7 +7,7 @@ alwaysApply: false
This rule enforces security best practices to prevent Server-Side Request Forgery (SSRF) vulnerabilities in Python applications, as defined in OWASP Top 10:2021-A10.
-
+```yaml
name: python_ssrf
description: Detect and prevent Server-Side Request Forgery (SSRF) vulnerabilities in Python applications as defined in OWASP Top 10:2021-A10
filters:
@@ -22,59 +22,59 @@ actions:
# Pattern 1: Detect direct use of requests library with user input
- pattern: "requests\\.(get|post|put|delete|head|options|patch)\\([^)]*?\\b(request\\.\\w+|params\\[\\'[^\\']+\\'\\]|data\\[\\'[^\\']+\\'\\]|json\\[\\'[^\\']+\\'\\]|args\\.get|form\\.get)"
message: "Potential SSRF vulnerability detected. User-controlled input is being used directly in HTTP requests. Implement URL validation and allowlisting."
-
+
# Pattern 2: Detect urllib usage with user input
- pattern: "urllib\\.(request|parse)\\.\\w+\\([^)]*?\\b(request\\.\\w+|params\\[\\'[^\\']+\\'\\]|data\\[\\'[^\\']+\\'\\]|json\\[\\'[^\\']+\\'\\]|args\\.get|form\\.get)"
message: "Potential SSRF vulnerability detected. User-controlled input is being used directly in urllib functions. Implement URL validation and allowlisting."
-
+
# Pattern 3: Detect http.client usage with user input
- pattern: "http\\.client\\.\\w+\\([^)]*?\\b(request\\.\\w+|params\\[\\'[^\\']+\\'\\]|data\\[\\'[^\\']+\\'\\]|json\\[\\'[^\\']+\\'\\]|args\\.get|form\\.get)"
message: "Potential SSRF vulnerability detected. User-controlled input is being used directly in http.client functions. Implement URL validation and allowlisting."
-
+
# Pattern 4: Detect aiohttp usage with user input
- pattern: "aiohttp\\.\\w+\\([^)]*?\\b(request\\.\\w+|params\\[\\'[^\\']+\\'\\]|data\\[\\'[^\\']+\\'\\]|json\\[\\'[^\\']+\\'\\]|args\\.get|form\\.get)"
message: "Potential SSRF vulnerability detected. User-controlled input is being used directly in aiohttp functions. Implement URL validation and allowlisting."
-
+
# Pattern 5: Detect httpx usage with user input
- pattern: "httpx\\.\\w+\\([^)]*?\\b(request\\.\\w+|params\\[\\'[^\\']+\\'\\]|data\\[\\'[^\\']+\\'\\]|json\\[\\'[^\\']+\\'\\]|args\\.get|form\\.get)"
message: "Potential SSRF vulnerability detected. User-controlled input is being used directly in httpx functions. Implement URL validation and allowlisting."
-
+
# Pattern 6: Detect pycurl usage with user input
- pattern: "pycurl\\.\\w+\\([^)]*?\\b(request\\.\\w+|params\\[\\'[^\\']+\\'\\]|data\\[\\'[^\\']+\\'\\]|json\\[\\'[^\\']+\\'\\]|args\\.get|form\\.get)"
message: "Potential SSRF vulnerability detected. User-controlled input is being used directly in pycurl functions. Implement URL validation and allowlisting."
-
+
# Pattern 7: Detect subprocess calls with user input that might lead to SSRF
- pattern: "subprocess\\.(Popen|call|run|check_output|check_call)\\([^)]*?\\b(request\\.\\w+|params\\[\\'[^\\']+\\'\\]|data\\[\\'[^\\']+\\'\\]|json\\[\\'[^\\']+\\'\\]|args\\.get|form\\.get)"
message: "Potential SSRF vulnerability detected. User-controlled input is being used in subprocess calls, which might lead to SSRF. Validate and sanitize input."
-
+
# Pattern 8: Detect os.system calls with user input that might lead to SSRF
- pattern: "os\\.(system|popen|spawn)\\([^)]*?\\b(request\\.\\w+|params\\[\\'[^\\']+\\'\\]|data\\[\\'[^\\']+\\'\\]|json\\[\\'[^\\']+\\'\\]|args\\.get|form\\.get)"
message: "Potential SSRF vulnerability detected. User-controlled input is being used in OS commands, which might lead to SSRF. Validate and sanitize input."
-
+
# Pattern 9: Detect URL construction with user input
- pattern: "(f|r)[\"\']https?://[^\"\']*?\\{[^\\}]*?\\b(request\\.\\w+|params\\[\\'[^\\']+\\'\\]|data\\[\\'[^\\']+\\'\\]|json\\[\\'[^\\']+\\'\\]|args\\.get|form\\.get)"
message: "Potential SSRF vulnerability detected. User-controlled input is being used in URL construction. Implement URL validation and allowlisting."
-
+
# Pattern 10: Detect URL joining with user input
- pattern: "urljoin\\([^,]+,[^)]*?\\b(request\\.\\w+|params\\[\\'[^\\']+\\'\\]|data\\[\\'[^\\']+\\'\\]|json\\[\\'[^\\']+\\'\\]|args\\.get|form\\.get)"
message: "Potential SSRF vulnerability detected. User-controlled input is being used in URL joining. Implement URL validation and allowlisting."
-
+
# Pattern 11: Detect file opening with user input (potential local SSRF)
- pattern: "open\\([^,]*?\\b(request\\.\\w+|params\\[\\'[^\\']+\\'\\]|data\\[\\'[^\\']+\\'\\]|json\\[\\'[^\\']+\\'\\]|args\\.get|form\\.get)"
message: "Potential local SSRF vulnerability detected. User-controlled input is being used in file operations. Validate file paths and use path sanitization."
-
+
# Pattern 12: Detect XML/YAML parsing with user input (potential XXE leading to SSRF)
- pattern: "(ET\\.fromstring|ET\\.parse|ET\\.XML|minidom\\.parse|parseString|yaml\\.load)\\([^)]*?\\b(request\\.\\w+|params\\[\\'[^\\']+\\'\\]|data\\[\\'[^\\']+\\'\\]|json\\[\\'[^\\']+\\'\\]|args\\.get|form\\.get)"
message: "Potential XXE vulnerability that could lead to SSRF detected. User-controlled input is being used in XML/YAML parsing. Use safe parsing methods and disable external entities."
-
+
# Pattern 13: Detect socket connections with user input
- pattern: "socket\\.(socket|create_connection)\\([^)]*?\\b(request\\.\\w+|params\\[\\'[^\\']+\\'\\]|data\\[\\'[^\\']+\\'\\]|json\\[\\'[^\\']+\\'\\]|args\\.get|form\\.get)"
message: "Potential SSRF vulnerability detected. User-controlled input is being used in socket connections. Implement host/port validation and allowlisting."
-
+
# Pattern 14: Detect FTP connections with user input
- pattern: "ftplib\\.FTP\\([^)]*?\\b(request\\.\\w+|params\\[\\'[^\\']+\\'\\]|data\\[\\'[^\\']+\\'\\]|json\\[\\'[^\\']+\\'\\]|args\\.get|form\\.get)"
message: "Potential SSRF vulnerability detected. User-controlled input is being used in FTP connections. Implement host validation and allowlisting."
-
+
# Pattern 15: Detect missing URL validation before making requests
- pattern: "def\\s+\\w+\\([^)]*?\\):[^\\n]*?\\n(?:[^\\n]*?\\n)*?[^\\n]*?requests\\.(get|post|put|delete|head|options|patch)\\([^)]*?url\\s*=\\s*[^\\n]*?(?!.*?validate_url)"
message: "Missing URL validation before making HTTP requests. Implement URL validation with allowlisting to prevent SSRF attacks."
@@ -82,7 +82,7 @@ actions:
- type: suggest
message: |
**Python Server-Side Request Forgery (SSRF) Prevention Best Practices:**
-
+
1. **URL Validation and Allowlisting:**
- Implement strict URL validation
- Use allowlists for domains, IP ranges, and protocols
@@ -92,41 +92,41 @@ actions:
import socket
import ipaddress
from urllib.parse import urlparse
-
+
def is_valid_url(url, allowed_domains=None, allowed_protocols=None, block_private_ips=True):
"""
Validate URLs against allowlists and block private IPs.
-
+
Args:
url (str): The URL to validate
allowed_domains (list): List of allowed domains
allowed_protocols (list): List of allowed protocols
block_private_ips (bool): Whether to block private IPs
-
+
Returns:
bool: True if URL is valid according to rules
"""
if not url:
return False
-
+
# Default allowlists if none provided
if allowed_domains is None:
allowed_domains = ["example.com", "api.example.com"]
if allowed_protocols is None:
allowed_protocols = ["https"]
-
+
try:
# Parse URL
parsed_url = urlparse(url)
-
+
# Check protocol
if parsed_url.scheme not in allowed_protocols:
return False
-
+
# Check domain against allowlist
if parsed_url.netloc not in allowed_domains:
return False
-
+
# Block private IPs if enabled
if block_private_ips:
hostname = parsed_url.netloc.split(':')[0]
@@ -142,38 +142,38 @@ actions:
except socket.gaierror:
# DNS resolution failed
return False
-
+
return True
except Exception:
return False
-
+
# Usage example
def fetch_resource(resource_url):
if not is_valid_url(resource_url):
raise ValueError("Invalid or disallowed URL")
-
+
# Proceed with request
import requests
return requests.get(resource_url)
```
-
+
2. **Implement Network-Level Controls:**
- Use network-level allowlists
- Configure firewalls to block outbound requests to internal resources
- Example with proxy configuration:
```python
import requests
-
+
def safe_request(url):
# Configure proxy that implements URL filtering
proxies = {
'http': 'http://ssrf-protecting-proxy:8080',
'https': 'http://ssrf-protecting-proxy:8080'
}
-
+
# Set timeout to prevent long-running requests
timeout = 10
-
+
try:
return requests.get(url, proxies=proxies, timeout=timeout)
except requests.exceptions.RequestException as e:
@@ -181,7 +181,7 @@ actions:
logging.error(f"Request failed: {e}")
return None
```
-
+
3. **Use Safe Libraries and Wrappers:**
- Create wrapper functions for HTTP requests
- Implement consistent security controls
@@ -189,77 +189,77 @@ actions:
```python
import requests
from urllib.parse import urlparse
-
+
class SafeRequestHandler:
def __init__(self, allowed_domains=None, allowed_protocols=None):
self.allowed_domains = allowed_domains or ["api.example.com"]
self.allowed_protocols = allowed_protocols or ["https"]
-
+
def validate_url(self, url):
parsed_url = urlparse(url)
-
+
# Validate protocol
if parsed_url.scheme not in self.allowed_protocols:
return False
-
+
# Validate domain
if parsed_url.netloc not in self.allowed_domains:
return False
-
+
return True
-
+
def request(self, method, url, **kwargs):
if not self.validate_url(url):
raise ValueError(f"URL validation failed for: {url}")
-
+
# Set sensible defaults
kwargs.setdefault('timeout', 10)
-
+
# Make the request
return requests.request(method, url, **kwargs)
-
+
def get(self, url, **kwargs):
return self.request('GET', url, **kwargs)
-
+
def post(self, url, **kwargs):
return self.request('POST', url, **kwargs)
-
+
# Usage
safe_requests = SafeRequestHandler()
response = safe_requests.get('https://api.example.com/data')
```
-
+
4. **Disable Redirects or Implement Redirect Validation:**
- Disable automatic redirects
- Validate each redirect location
- Example:
```python
import requests
-
+
def safe_request_with_redirect_validation(url, allowed_domains):
# Disable automatic redirects
session = requests.Session()
response = session.get(url, allow_redirects=False)
-
+
# Handle redirects manually with validation
redirect_count = 0
max_redirects = 5
-
+
while 300 <= response.status_code < 400 and redirect_count < max_redirects:
redirect_url = response.headers.get('Location')
-
+
# Validate redirect URL
parsed_url = urlparse(redirect_url)
if parsed_url.netloc not in allowed_domains:
raise ValueError(f"Redirect to disallowed domain: {parsed_url.netloc}")
-
+
# Follow the redirect with validation
redirect_count += 1
response = session.get(redirect_url, allow_redirects=False)
-
+
return response
```
-
+
5. **Use Metadata Instead of Direct URLs:**
- Use resource identifiers instead of URLs
- Resolve identifiers server-side
@@ -272,16 +272,16 @@ actions:
"product_data": "https://api.example.com/products/",
"weather_info": "https://api.weather.com/forecast/"
}
-
+
# Check if resource_id is in allowed list
if resource_id not in resource_map:
raise ValueError(f"Unknown resource ID: {resource_id}")
-
+
# Construct URL from safe base + ID
base_url = resource_map[resource_id]
return requests.get(base_url)
```
-
+
6. **Implement Response Handling Controls:**
- Sanitize and validate responses
- Prevent response data from being used in further requests
@@ -289,16 +289,16 @@ actions:
```python
def safe_request_with_response_validation(url):
response = requests.get(url)
-
+
# Check response size
if len(response.content) > MAX_RESPONSE_SIZE:
raise ValueError("Response too large")
-
+
# Validate content type
content_type = response.headers.get('Content-Type', '')
if not content_type.startswith('application/json'):
raise ValueError(f"Unexpected content type: {content_type}")
-
+
# Parse and validate JSON structure
try:
data = response.json()
@@ -309,7 +309,7 @@ actions:
except ValueError:
raise ValueError("Invalid JSON response")
```
-
+
7. **Use Timeouts and Circuit Breakers:**
- Set appropriate timeouts
- Implement circuit breakers for failing services
@@ -317,7 +317,7 @@ actions:
```python
import requests
from requests.exceptions import Timeout, ConnectionError
-
+
def request_with_circuit_breaker(url, max_retries=3, timeout=5):
retries = 0
while retries < max_retries:
@@ -331,7 +331,7 @@ actions:
# Exponential backoff
time.sleep(2 ** retries)
```
-
+
8. **Implement Proper Logging and Monitoring:**
- Log all outbound requests
- Monitor for unusual patterns
@@ -339,11 +339,11 @@ actions:
```python
import logging
import requests
-
+
def logged_request(url, **kwargs):
# Log the outbound request
logging.info(f"Outbound request to: {url}")
-
+
try:
response = requests.get(url, **kwargs)
# Log the response
@@ -354,7 +354,7 @@ actions:
logging.error(f"Request to {url} failed: {str(e)}")
raise
```
-
+
9. **Use DNS Resolution Controls:**
- Implement DNS resolution controls
- Block internal DNS names
@@ -362,37 +362,37 @@ actions:
```python
import socket
import ipaddress
-
+
def is_safe_host(hostname):
try:
# Resolve hostname to IP
ip_addresses = socket.getaddrinfo(
hostname, None, socket.AF_INET, socket.SOCK_STREAM
)
-
+
for family, socktype, proto, canonname, sockaddr in ip_addresses:
ip = sockaddr[0]
ip_obj = ipaddress.ip_address(ip)
-
+
# Check if IP is private/internal
- if (ip_obj.is_private or ip_obj.is_loopback or
+ if (ip_obj.is_private or ip_obj.is_loopback or
ip_obj.is_link_local or ip_obj.is_reserved):
return False
-
+
return True
except (socket.gaierror, ValueError):
return False
-
+
def safe_request_with_dns_check(url):
parsed_url = urlparse(url)
hostname = parsed_url.netloc.split(':')[0]
-
+
if not is_safe_host(hostname):
raise ValueError(f"Hostname resolves to unsafe IP: {hostname}")
-
+
return requests.get(url)
```
-
+
10. **Implement Defense in Depth:**
- Combine multiple protection mechanisms
- Don't rely on a single control
@@ -404,19 +404,19 @@ actions:
self.allowed_protocols = ["https"]
self.max_redirects = 3
self.timeout = 10
-
+
def is_safe_url(self, url):
# URL validation
parsed_url = urlparse(url)
-
+
# Protocol check
if parsed_url.scheme not in self.allowed_protocols:
return False
-
+
# Domain check
if parsed_url.netloc not in self.allowed_domains:
return False
-
+
# DNS resolution check
hostname = parsed_url.netloc.split(':')[0]
try:
@@ -430,47 +430,47 @@ actions:
return False
except socket.gaierror:
return False
-
+
return True
-
+
def request(self, method, url, **kwargs):
# Validate URL
if not self.is_safe_url(url):
raise ValueError(f"URL failed security validation: {url}")
-
+
# Set sensible defaults
kwargs.setdefault('timeout', self.timeout)
kwargs.setdefault('allow_redirects', False)
-
+
# Make initial request
session = requests.Session()
response = session.request(method, url, **kwargs)
-
+
# Handle redirects manually with validation
redirect_count = 0
-
+
while 300 <= response.status_code < 400 and redirect_count < self.max_redirects:
redirect_url = response.headers.get('Location')
-
+
# Validate redirect URL
if not self.is_safe_url(redirect_url):
raise ValueError(f"Redirect URL failed security validation: {redirect_url}")
-
+
# Follow the redirect with validation
redirect_count += 1
response = session.request(method, redirect_url, **kwargs)
-
+
# Log the request
logging.info(f"{method} request to {url} completed with status {response.status_code}")
-
+
return response
-
+
def get(self, url, **kwargs):
return self.request('GET', url, **kwargs)
-
+
def post(self, url, **kwargs):
return self.request('POST', url, **kwargs)
-
+
# Usage
client = SSRFProtectedClient()
response = client.get('https://api.example.com/data')
@@ -481,15 +481,15 @@ actions:
# Check 1: URL validation implementation
- pattern: "def\\s+is_valid_url|def\\s+validate_url"
message: "URL validation function is implemented."
-
+
# Check 2: Allowlist implementation
- pattern: "allowed_domains|allowed_urls|ALLOWED_HOSTS|whitelist"
message: "URL allowlisting is implemented."
-
+
# Check 3: Safe request wrapper
- pattern: "class\\s+\\w+Request|def\\s+safe_request"
message: "Safe request wrapper is implemented."
-
+
# Check 4: IP address validation
- pattern: "ipaddress\\.ip_address|is_private|is_loopback|is_reserved"
message: "IP address validation is implemented to prevent access to internal resources."
@@ -517,4 +517,5 @@ metadata:
- "https://docs.python.org/3/library/urllib.request.html"
- "https://docs.python-requests.org/en/latest/user/advanced/#ssl-cert-verification"
- "https://docs.python.org/3/library/ipaddress.html"
-
\ No newline at end of file
+```
+
diff --git a/.cursor/rules/python-vulnerable-outdated-components.mdc b/.cursor/rules/python-vulnerable-outdated-components.mdc
index be3380d..0e8efac 100644
--- a/.cursor/rules/python-vulnerable-outdated-components.mdc
+++ b/.cursor/rules/python-vulnerable-outdated-components.mdc
@@ -7,7 +7,7 @@ alwaysApply: false
This rule enforces security best practices to prevent vulnerabilities related to outdated dependencies and components in Python applications, as defined in OWASP Top 10:2021-A06.
-
+```yaml
name: python_vulnerable_outdated_components
description: Detect and prevent vulnerabilities related to outdated dependencies and components in Python applications as defined in OWASP Top 10:2021-A06
filters:
@@ -23,59 +23,59 @@ actions:
- pattern: "^(django|flask|fastapi|requests|cryptography|pyyaml|sqlalchemy|celery|numpy|pandas|pillow|tensorflow|torch|boto3|psycopg2)\\s*$"
file_pattern: "requirements.*\\.txt$|setup\\.py$|pyproject\\.toml$"
message: "Unpinned dependency detected. Always pin dependencies to specific versions to prevent automatic updates to potentially vulnerable versions."
-
+
# Pattern 2: Outdated/vulnerable Django versions
- pattern: "django([<>=]=|~=|==)\\s*[\"']?(1\\.|2\\.[0-2]\\.|3\\.[0-2]\\.|4\\.0\\.)[0-9]+[\"']?"
message: "Potentially outdated Django version detected. Consider upgrading to the latest stable version with security updates."
-
+
# Pattern 3: Outdated/vulnerable Flask versions
- pattern: "flask([<>=]=|~=|==)\\s*[\"']?(0\\.|1\\.[0-3]\\.|2\\.0\\.[0-3])[0-9]*[\"']?"
message: "Potentially outdated Flask version detected. Consider upgrading to the latest stable version with security updates."
-
+
# Pattern 4: Outdated/vulnerable Requests versions
- pattern: "requests([<>=]=|~=|==)\\s*[\"']?(0\\.|1\\.|2\\.[0-2][0-5]\\.[0-9]+)[\"']?"
message: "Potentially outdated Requests version detected. Consider upgrading to the latest stable version with security updates."
-
+
# Pattern 5: Outdated/vulnerable Cryptography versions
- pattern: "cryptography([<>=]=|~=|==)\\s*[\"']?(0\\.|1\\.|2\\.|3\\.[0-3]\\.|3\\.4\\.[0-7])[0-9]*[\"']?"
message: "Potentially outdated Cryptography version detected. Consider upgrading to the latest stable version with security updates."
-
+
# Pattern 6: Outdated/vulnerable PyYAML versions
- pattern: "pyyaml([<>=]=|~=|==)\\s*[\"']?(0\\.|1\\.|2\\.|3\\.|4\\.|5\\.[0-5]\\.[0-9]+)[\"']?"
message: "Potentially outdated PyYAML version detected. Consider upgrading to the latest stable version with security updates."
-
+
# Pattern 7: Outdated/vulnerable Pillow versions
- pattern: "pillow([<>=]=|~=|==)\\s*[\"']?(0\\.|1\\.|2\\.|3\\.|4\\.|5\\.|6\\.|7\\.|8\\.[0-3]\\.[0-9]+)[\"']?"
message: "Potentially outdated Pillow version detected. Consider upgrading to the latest stable version with security updates."
-
+
# Pattern 8: Direct imports of deprecated modules
- pattern: "from\\s+xml\\.etree\\.ElementTree\\s+import\\s+.*parse|from\\s+urllib2\\s+import|from\\s+urllib\\s+import\\s+urlopen|import\\s+cgi|import\\s+imp"
message: "Use of deprecated or insecure module detected. Consider using more secure alternatives."
-
+
# Pattern 9: Use of deprecated functions
- pattern: "\\.set_password\\([^)]*\\)|hashlib\\.md5\\(|hashlib\\.sha1\\(|random\\.random\\(|random\\.randrange\\(|random\\.randint\\("
message: "Use of deprecated or insecure function detected. Consider using more secure alternatives."
-
+
# Pattern 10: Insecure dependency loading
- pattern: "__import__\\(|importlib\\.import_module\\(|exec\\(|eval\\("
message: "Dynamic code execution or module loading detected. This can lead to code injection if user input is involved."
-
+
# Pattern 11: Outdated TLS/SSL versions
- pattern: "ssl\\.PROTOCOL_TLSv1|ssl\\.PROTOCOL_TLSv1_1|ssl\\.PROTOCOL_SSLv2|ssl\\.PROTOCOL_SSLv3|ssl\\.PROTOCOL_TLSv1_2"
message: "Outdated TLS/SSL protocol version detected. Use ssl.PROTOCOL_TLS_CLIENT or ssl.PROTOCOL_TLS_SERVER instead."
-
+
# Pattern 12: Insecure deserialization libraries
- pattern: "import\\s+pickle|import\\s+marshal|import\\s+shelve"
message: "Use of potentially insecure deserialization library detected. Ensure these are not used with untrusted data."
-
+
# Pattern 13: Outdated/vulnerable SQLAlchemy versions
- pattern: "sqlalchemy([<>=]=|~=|==)\\s*[\"']?(0\\.|1\\.[0-3]\\.[0-9]+)[\"']?"
message: "Potentially outdated SQLAlchemy version detected. Consider upgrading to the latest stable version with security updates."
-
+
# Pattern 14: Outdated/vulnerable Celery versions
- pattern: "celery([<>=]=|~=|==)\\s*[\"']?(0\\.|1\\.|2\\.|3\\.|4\\.[0-4]\\.[0-9]+)[\"']?"
message: "Potentially outdated Celery version detected. Consider upgrading to the latest stable version with security updates."
-
+
# Pattern 15: Insecure package installation
- pattern: "pip\\s+install\\s+.*--no-deps|pip\\s+install\\s+.*--user|pip\\s+install\\s+.*--pre|pip\\s+install\\s+.*--index-url\\s+http://"
message: "Insecure pip installation options detected. Avoid using --no-deps, ensure HTTPS for index URLs, and be cautious with --pre and --user flags."
@@ -83,7 +83,7 @@ actions:
- type: suggest
message: |
**Python Dependency and Component Security Best Practices:**
-
+
1. **Dependency Management:**
- Always pin dependencies to specific versions
- Use a lockfile (requirements.txt, Pipfile.lock, poetry.lock)
@@ -93,7 +93,7 @@ actions:
requests==2.31.0
cryptography==41.0.5
```
-
+
2. **Vulnerability Scanning:**
- Regularly scan dependencies for vulnerabilities
- Use tools like safety, pip-audit, or dependabot
@@ -102,7 +102,7 @@ actions:
pip install safety
safety check -r requirements.txt
```
-
+
3. **Dependency Updates:**
- Establish a regular update schedule
- Automate updates with tools like Renovate or Dependabot
@@ -123,7 +123,7 @@ actions:
pip install pip-upgrader
pip-upgrader -p requirements.txt
```
-
+
4. **Secure Package Installation:**
- Use trusted package sources
- Verify package integrity with hashes
@@ -132,7 +132,7 @@ actions:
# requirements.txt
Django==4.2.7 --hash=sha256:8e0f1c2c2786b5c0e39fe1afce24c926040fad47c8ea8ad30aaa2c03b76293b8
```
-
+
5. **Minimal Dependencies:**
- Limit the number of dependencies
- Regularly audit and remove unused dependencies
@@ -142,7 +142,7 @@ actions:
pip install pipdeptree
pipdeptree --warn silence | grep -v "^\s"
```
-
+
6. **Virtual Environments:**
- Use isolated environments for each project
- Document environment setup
@@ -152,7 +152,7 @@ actions:
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt
```
-
+
7. **Container Security:**
- Use official base images
- Pin image versions
@@ -160,18 +160,18 @@ actions:
- Example Dockerfile:
```dockerfile
FROM python:3.11-slim@sha256:1234567890abcdef
-
+
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
-
+
COPY . .
RUN pip install --no-cache-dir -e .
-
+
USER nobody
CMD ["gunicorn", "myapp.wsgi:application"]
```
-
+
8. **Compile-time Dependencies:**
- Separate runtime and development dependencies
- Example with pip-tools:
@@ -179,13 +179,13 @@ actions:
# requirements.in
Django>=4.2,<5.0
requests>=2.31.0
-
+
# dev-requirements.in
-r requirements.in
pytest>=7.0.0
black>=23.0.0
```
-
+
9. **Deprecated API Usage:**
- Stay informed about deprecation notices
- Plan migrations away from deprecated APIs
@@ -193,7 +193,7 @@ actions:
```bash
python manage.py check --deploy
```
-
+
10. **Supply Chain Security:**
- Use tools like pip-audit to check for supply chain attacks
- Consider using a private PyPI mirror
@@ -209,16 +209,16 @@ actions:
- pattern: "^[a-zA-Z0-9_-]+==\\d+\\.\\d+\\.\\d+"
file_pattern: "requirements.*\\.txt$"
message: "Dependencies are properly pinned to specific versions."
-
+
# Check 2: Use of dependency scanning tools
- pattern: "safety|pip-audit|pyup|dependabot|renovate"
file_pattern: "\\.github/workflows/.*\\.ya?ml$|\\.gitlab-ci\\.ya?ml$|tox\\.ini$|setup\\.py$|pyproject\\.toml$"
message: "Dependency scanning tools are being used."
-
+
# Check 3: Modern TLS usage
- pattern: "ssl\\.PROTOCOL_TLS_CLIENT|ssl\\.PROTOCOL_TLS_SERVER|ssl\\.create_default_context\\(\\)"
message: "Using secure TLS protocol versions."
-
+
# Check 4: Secure random generation
- pattern: "secrets\\.token_|secrets\\.choice|cryptography\\.hazmat"
message: "Using secure random generation methods."
@@ -248,4 +248,5 @@ metadata:
- "https://github.com/pyupio/safety-db"
- "https://github.com/pypa/advisory-database"
- "https://python-security.readthedocs.io/packages.html"
-
\ No newline at end of file
+```
+
diff --git a/.cursor/rules/react-patterns.mdc b/.cursor/rules/react-patterns.mdc
index 3dcab70..56af8a1 100644
--- a/.cursor/rules/react-patterns.mdc
+++ b/.cursor/rules/react-patterns.mdc
@@ -6,7 +6,7 @@ globs: *.jsx, *.tsx
Ensures React components follow recommended patterns and hook usage.
-
+```yaml
name: react_patterns
description: Enforce React component patterns and hooks best practices
filters:
@@ -37,4 +37,6 @@ actions:
metadata:
priority: high
version: 1.0
-
\ No newline at end of file
+```
+
+
diff --git a/.cursor/rules/readme-maintenance-standards.mdc b/.cursor/rules/readme-maintenance-standards.mdc
index 3c198a7..12a22f6 100644
--- a/.cursor/rules/readme-maintenance-standards.mdc
+++ b/.cursor/rules/readme-maintenance-standards.mdc
@@ -7,7 +7,7 @@ alwaysApply: false
Ensures that README files are consistently maintained, up-to-date, and informative.
-
+```yaml
name: enhanced_readme_maintenance_standards
description: Enforce standards for maintaining README documentation
filters:
@@ -67,4 +67,5 @@ actions:
metadata:
priority: high
version: 1.1
-
\ No newline at end of file
+```
+
diff --git a/.cursor/rules/secret-detection.mdc b/.cursor/rules/secret-detection.mdc
index 8c414af..ac3e4ee 100644
--- a/.cursor/rules/secret-detection.mdc
+++ b/.cursor/rules/secret-detection.mdc
@@ -2,7 +2,7 @@
This rule helps identify potential secrets, credentials, and sensitive data in code files to prevent accidental exposure or leakage. It provides warnings when secrets are detected and suggests best practices for secure secret management.
-
+```yaml
name: secret_detection_warning
description: Detect and warn about potential secrets and sensitive data in code files
filters:
@@ -86,51 +86,51 @@ actions:
- type: suggest
message: |
**Secure Secret Management Best Practices:**
-
+
1. **Never hardcode secrets in source code**
- Secrets in code can be exposed via version control, logs, or screenshots
- Code is often shared, backed up, and stored in multiple locations
-
+
2. **Use environment variables for configuration**
- Load secrets from environment variables at runtime
- Use libraries like dotenv, but ensure .env files are in .gitignore
- Example: `API_KEY=os.environ.get("API_KEY")`
-
+
3. **Implement secret rotation**
- Regularly rotate credentials and keys
- Use short-lived tokens when possible
- Implement proper secret lifecycle management
-
+
4. **Use secrets management solutions**
- AWS Secrets Manager, Azure Key Vault, HashiCorp Vault
- Platform-specific solutions like Kubernetes Secrets
- These provide encryption, access control, and audit trails
-
+
5. **Implement access controls**
- Limit who can access secrets
- Use the principle of least privilege
- Implement proper authentication for secret access
-
+
6. **Use .gitignore and .cursorignore**
- Add patterns for files that might contain secrets
- Example patterns: `.env`, `*.key`, `*secret*`, `*.pem`
- Verify these files are not committed to version control
-
+
7. **Consider using secure by default libraries**
- Libraries that separate configuration from code
- Frameworks with built-in secrets management
- Encryption libraries with secure defaults
-
+
8. **Implement detection tools**
- Use pre-commit hooks to prevent secret leakage
- Implement scanning in CI/CD pipelines
- Consider tools like git-secrets, trufflehog, or detect-secrets
-
+
9. **Audit and monitor**
- Regularly audit code for leaked secrets
- Monitor for unauthorized access to secrets
- Implement alerts for potential compromises
-
+
10. **Educate your team**
- Train developers on secure secret management
- Establish clear procedures for handling secrets
@@ -140,13 +140,13 @@ actions:
conditions:
- pattern: "(?i)import\\s+os\\s*;?\\s*.*\\s+os\\.environ(\\.get)?"
message: "Environment variable usage detected, which is a good practice for managing secrets."
-
+
- pattern: "(?i)process\\.env\\."
message: "Environment variable usage in JavaScript detected, which is a good practice for managing secrets."
-
+
- pattern: "(?i)dotenv"
message: "Dotenv library usage detected, which can help with environment variable management."
-
+
- pattern: "(?i)(secret[s]?[_-]?manager|key[_-]?vault|hashicorp|vault)"
message: "Secret management solution reference detected, which is a best practice for handling secrets."
@@ -165,4 +165,5 @@ metadata:
- "https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning"
- "https://cloud.google.com/secret-manager/docs/best-practices"
- "https://aws.amazon.com/blogs/security/how-to-use-aws-secrets-manager-securely-store-rotate-deploy-database-credentials/"
-
\ No newline at end of file
+```
+
diff --git a/.cursor/rules/security-practices.mdc b/.cursor/rules/security-practices.mdc
index 0e012cc..9b3003c 100644
--- a/.cursor/rules/security-practices.mdc
+++ b/.cursor/rules/security-practices.mdc
@@ -7,7 +7,7 @@ alwaysApply: false
Ensures application security standards are maintained.
-
+```yaml
name: security_practices
description: Enforce security best practices across the application
filters:
@@ -40,4 +40,6 @@ actions:
metadata:
priority: critical
version: 1.0
-
\ No newline at end of file
+```
+
+
diff --git a/.cursor/rules/tailwind-standards.mdc b/.cursor/rules/tailwind-standards.mdc
index cd41b93..82773d2 100644
--- a/.cursor/rules/tailwind-standards.mdc
+++ b/.cursor/rules/tailwind-standards.mdc
@@ -6,7 +6,7 @@ globs: *.vue, *.jsx, *.tsx, *.html
Ensures consistent and optimized usage of Tailwind CSS classes.
-
+```yaml
name: tailwind_standards
description: Enforce Tailwind CSS best practices and organization
filters:
@@ -34,4 +34,6 @@ actions:
metadata:
priority: medium
version: 1.0
-
\ No newline at end of file
+```
+
+
diff --git a/.cursor/rules/testing-guidelines.mdc b/.cursor/rules/testing-guidelines.mdc
index 75a9772..31821cc 100644
--- a/.cursor/rules/testing-guidelines.mdc
+++ b/.cursor/rules/testing-guidelines.mdc
@@ -1,6 +1,6 @@
---
description: Testing Guidelines
-globs:
+globs:
alwaysApply: false
---
# Revised Cursor Rule File - Testing Guidelines (preserving functionality)
@@ -35,4 +35,4 @@ rules:
guidelines:
- "Clearly delineate test types (unit, integration, end-to-end) and ensure each is executed in appropriate environments."
- "Isolate tests to avoid side effects, and clean up any test data or state after execution."
- - "Integrate tests into continuous integration workflows to run automatically without requiring changes to production code."
\ No newline at end of file
+ - "Integrate tests into continuous integration workflows to run automatically without requiring changes to production code."
diff --git a/.cursor/rules/tests-documentation-maintenance.mdc b/.cursor/rules/tests-documentation-maintenance.mdc
index f5e4a1d..170a5a1 100644
--- a/.cursor/rules/tests-documentation-maintenance.mdc
+++ b/.cursor/rules/tests-documentation-maintenance.mdc
@@ -6,7 +6,7 @@ globs: *.php, *.feature, README.md, *.md
Ensures that tests are written and updated for Drupal modules and plugins, and that documentation remains current.
-
+```yaml
name: tests_documentation_maintenance
description: Require tests for new functionality and enforce documentation updates.
filters:
@@ -39,4 +39,5 @@ actions:
metadata:
priority: high
version: 1.0
-
+```
+
diff --git a/.cursor/rules/third-party-integration.mdc b/.cursor/rules/third-party-integration.mdc
index f7fabcf..7422ab4 100644
--- a/.cursor/rules/third-party-integration.mdc
+++ b/.cursor/rules/third-party-integration.mdc
@@ -6,7 +6,7 @@ globs: *.php, *.js, *.ts
Ensures consistent and secure third-party service integration.
-
+```yaml
name: third_party_integration
description: Enforce standards for external service integration
filters:
@@ -34,4 +34,6 @@ actions:
metadata:
priority: high
version: 1.0
-
\ No newline at end of file
+```
+
+
diff --git a/.cursor/rules/vortex-cicd-standards.mdc b/.cursor/rules/vortex-cicd-standards.mdc
index d62afab..b620da8 100644
--- a/.cursor/rules/vortex-cicd-standards.mdc
+++ b/.cursor/rules/vortex-cicd-standards.mdc
@@ -6,7 +6,7 @@ globs: .circleci/config.yml, renovate.json, .github/workflows/*.yml
Ensures proper CI/CD and dependency management configuration.
-
+```yaml
name: vortex_cicd_standards
description: Enforce standards for Vortex CI/CD and Renovate configuration
filters:
@@ -50,4 +50,6 @@ actions:
metadata:
priority: critical
version: 1.0
-
\ No newline at end of file
+```
+
+
diff --git a/.cursor/rules/vortex-scaffold-standards.mdc b/.cursor/rules/vortex-scaffold-standards.mdc
index 897e5da..7494623 100644
--- a/.cursor/rules/vortex-scaffold-standards.mdc
+++ b/.cursor/rules/vortex-scaffold-standards.mdc
@@ -6,7 +6,7 @@ globs: *.yml, *.sh, composer.json, README.md
Ensures proper usage of Vortex/DrevOps scaffold features and workflows.
-
+```yaml
name: vortex_scaffold_standards
description: Enforce standards for Vortex/DrevOps scaffold usage
filters:
@@ -54,4 +54,6 @@ actions:
metadata:
priority: high
version: 1.1
-
\ No newline at end of file
+```
+
+
diff --git a/.cursor/rules/vue-best-practices.mdc b/.cursor/rules/vue-best-practices.mdc
index f4da212..05e4651 100644
--- a/.cursor/rules/vue-best-practices.mdc
+++ b/.cursor/rules/vue-best-practices.mdc
@@ -6,7 +6,7 @@ globs: *.vue, *.js, *.ts
Ensures Vue 3 and NuxtJS code follows recommended patterns and optimizations.
-
+```yaml
name: vue_nuxt_best_practices
description: Enforce Vue 3 and NuxtJS coding standards and optimizations
filters:
@@ -37,4 +37,6 @@ actions:
metadata:
priority: high
version: 1.0
-
\ No newline at end of file
+```
+
+