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: "]*href=['\"]http" message: "External scripts or stylesheets without Subresource Integrity (SRI) checks detected. Add integrity and crossorigin attributes." - + # Pattern 5: Use of obsolete or removed modules - pattern: "module:\\s*('[^']*captcha'|'recaptcha'|'xmlrpc'|'openid'|'php')" message: "Potentially vulnerable or deprecated module detected. Consider using more secure alternatives." - + # Pattern 6: Hard-coded versions in composer.json - - pattern: "\"drupal/[^\"]+\":\\s*\"(~|\\^)?[0-9]\\.[0-9]\\.[0-9]\"" + - pattern: "\"drupal/[^\"]+\":\\s*\"(~|\\^)?[0-9]\\.[0-9]\\.[0-9]\"" message: "Hard-coded specific version detected in composer.json. Consider using version ranges to receive security updates." - + # Pattern 7: Outdated or insecure PHP API usage - pattern: "mysql_|split\\(|ereg\\(|eregi\\(|create_function\\(|each\\(" message: "Deprecated or insecure PHP function detected. Use modern alternatives for better security." - + # Pattern 8: Usage of contrib modules without version constraints - pattern: "type:\\s*module\\s*\\nname:" message: "Ensure your module specifies core_version_requirement to prevent installation on unsupported Drupal versions." - + # Pattern 9: Missing security advisories handling in composer.json - pattern: "composer\\.json" message: "Consider adding drupal/core-security-advisories as a dev dependency to detect known vulnerable packages." - + # Pattern 10: Direct usage of vulnerable sanitization functions - pattern: "check_plain\\(|filter_xss\\(|filter_xss_admin\\(" message: "Legacy text sanitization function detected. Use Html::escape() or Xss::filter() instead." @@ -62,35 +62,35 @@ actions: - type: suggest message: | **Drupal Component Security Best Practices:** - + 1. **Update Management:** - Keep Drupal core updated to the latest secure version - Subscribe to the Drupal Security Newsletter - Implement a regular update schedule (monthly at minimum) - Use security advisories checking in your development workflow - Implement Composer's security-advisories metadata - + 2. **Dependency Management:** - Use Composer for managing all dependencies - Specify version constraints that allow security updates - Add drupal/core-security-advisories as a dev dependency - Regularly run `composer update --with-dependencies` - Use `composer outdated` to identify outdated packages - + 3. **API Usage:** - Use modern Drupal APIs rather than deprecated functions - Migrate away from jQuery to modern JavaScript where possible - Implement Subresource Integrity (SRI) for external resources - Update custom code to use current best practices - Follow the Drupal API deprecation policies - + 4. **Security Monitoring:** - Implement automated vulnerability scanning in CI/CD - Use tools like Drupal Check or Upgrade Status module - Monitor the Drupal security advisories page - Implement automated updates for non-critical dependencies - Set up alerts for security issues in used components - + 5. **Module Management:** - Remove unused modules from your codebase - Prefer well-maintained modules with security teams @@ -103,15 +103,15 @@ actions: # Check 1: Proper core version requirement - pattern: "core_version_requirement:\\s*[\"']\\^(8\\.8|8\\.9|9|10)\\.[0-9]+[\"']" message: "Using proper core version requirements." - + # Check 2: Use of modern APIs - pattern: "\\\\Drupal::messenger\\(\\)|->messenger\\(\\)|\\\\Drupal::service\\('messenger'\\)" message: "Using modern message API instead of deprecated functions." - + # Check 3: Proper composer usage - pattern: "\"require\":\\s*\\{[^}]*\"drupal/core(-recommended)?\":\\s*\"\\^[0-9]+\\.[0-9]+\"" message: "Using proper version constraints in Composer." - + # Check 4: SRI implementation - pattern: "integrity=[\"'][a-zA-Z0-9\\+/=\\-_]+[\"']\\s+crossorigin=[\"']anonymous[\"']" message: "Properly implementing Subresource Integrity." @@ -136,4 +136,6 @@ metadata: - "https://www.drupal.org/docs/security-in-drupal/staying-up-to-date" - "https://www.drupal.org/docs/upgrading-drupal" - "https://www.drupal.org/docs/develop/using-composer/managing-dependencies-for-a-drupal-project" - \ No newline at end of file +``` + + diff --git a/.cursor/rules/generic_bash_style.mdc b/.cursor/rules/generic_bash_style.mdc index 45f08a8..4745783 100644 --- a/.cursor/rules/generic_bash_style.mdc +++ b/.cursor/rules/generic_bash_style.mdc @@ -1,12 +1,12 @@ --- description: Enforce general Bash scripting standards with enhanced logging -globs: +globs: --- # Enhanced Bash Scripting Standard with Colorized Logging This rule enforces best practices for writing Bash scripts, with an emphasis on using colorized logging for better output readability. - +```yaml name: enhanced_bash_style description: Enforce Bash scripting standards with colorized logging filters: @@ -68,4 +68,5 @@ actions: metadata: priority: medium version: 1.1 - \ No newline at end of file +``` + diff --git a/.cursor/rules/git-commit-standards.mdc b/.cursor/rules/git-commit-standards.mdc index ace1472..f5eeac2 100644 --- a/.cursor/rules/git-commit-standards.mdc +++ b/.cursor/rules/git-commit-standards.mdc @@ -6,7 +6,7 @@ globs: .git/* Ensures consistent Git commit messages. - +```yaml name: git_commit_standards description: Enforce structured Git commit messages. filters: @@ -47,4 +47,5 @@ actions: metadata: priority: high version: 1.1 - +``` + diff --git a/.cursor/rules/github-actions-standards.mdc b/.cursor/rules/github-actions-standards.mdc index 37abb6e..83d2a58 100644 --- a/.cursor/rules/github-actions-standards.mdc +++ b/.cursor/rules/github-actions-standards.mdc @@ -1,5 +1,5 @@ --- -description: +description: globs: .github/workflows/*.yml alwaysApply: false --- @@ -7,7 +7,7 @@ alwaysApply: false Ensures GitHub Actions workflows follow best practices and use the latest action versions. - +```yaml name: github_actions_standards description: Enforce standards for GitHub Actions workflows filters: @@ -62,4 +62,5 @@ metadata: - ci/cd - github - automation - \ No newline at end of file +``` + diff --git a/.cursor/rules/improve-cursorrules-efficiency.mdc b/.cursor/rules/improve-cursorrules-efficiency.mdc index b182364..3177a5f 100644 --- a/.cursor/rules/improve-cursorrules-efficiency.mdc +++ b/.cursor/rules/improve-cursorrules-efficiency.mdc @@ -6,7 +6,7 @@ globs: *.mdc Ensures Cursor analyzes AI query efficiency, detects repeated requests, and automatically updates relevant rules to improve response quality and reduce redundancy. - +```yaml name: ai_query_efficiency_optimization description: Analyze AI query efficiency, optimize rules, and prevent repeated requests. filters: @@ -88,7 +88,7 @@ examples: "Please rewrite this code to be more efficient." output: | Cursor detects inefficiency in queries and suggests: - + "I notice you're making multiple attempts. To get better results: 1. Specify which part of the module isn't working 2. Include any error messages you're seeing @@ -101,7 +101,7 @@ examples: "Try again with better practices." output: | Cursor detects repetition and suggests: - + "For better Lagoon configuration results: 1. Specify which services you need (nginx, php, mariadb, etc.) 2. Mention your project type (Drupal, WordPress, etc.) @@ -111,4 +111,5 @@ examples: metadata: priority: critical version: 1.2 - +``` + diff --git a/.cursor/rules/javascript-broken-access-control.mdc b/.cursor/rules/javascript-broken-access-control.mdc index 1eac7ec..dd8243a 100644 --- a/.cursor/rules/javascript-broken-access-control.mdc +++ b/.cursor/rules/javascript-broken-access-control.mdc @@ -6,7 +6,7 @@ globs: **/*.js, **/*.jsx, **/*.ts, **/*.tsx, !**/node_modules/**, !**/dist/**, ! This rule identifies and prevents broken access control vulnerabilities in JavaScript applications, focusing on both browser and Node.js environments, as defined in OWASP Top 10:2021-A01. - +```yaml name: javascript_broken_access_control description: Detect and prevent broken access control patterns in JavaScript applications as defined in OWASP Top 10:2021-A01 @@ -16,67 +16,67 @@ actions: # Pattern 1: Detect Direct Reference to User-Supplied IDs (IDOR vulnerability) - pattern: "(?:req|request)\\.(?:params|query|body)\\.(?:id|userId|recordId)[^\\n]*?(?:findById|getById|find\\(|get\\()" message: "Potential Insecure Direct Object Reference (IDOR) vulnerability. User-supplied IDs should be validated against user permissions before database access." - + # Pattern 2: Detect Missing Authorization Checks in Route Handlers - pattern: "(?:app|router)\\.(?:get|post|put|delete|patch)\\(['\"][^'\"]+['\"],\\s*(?:async)?\\s*\\(?(?:req|request),\\s*(?:res|response)(?:,[^\\)]+)?\\)?\\s*=>\\s*\\{[^\\}]*?\\}\\)" negative_pattern: "(?:isAuthenticated|isAuthorized|checkPermission|verifyAccess|auth\\.check|authenticate|authorize|userHasAccess|checkAuth|permissions\\.|requireAuth|requiresAuth|ensureAuth|\\bauth\\b|\\broles?\\b|\\bpermission\\b|\\baccess\\b)" message: "Route handler appears to be missing authorization checks. Implement proper access control to verify user permissions before processing requests." - + # Pattern 3: Detect JWT Token Validation Issues - pattern: "(?:jwt|jsonwebtoken)\\.verify\\((?:[^,]+),\\s*['\"]((?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?)['\"]" message: "Hardcoded JWT secret detected. Store JWT secrets securely in environment variables or a configuration manager." - + # Pattern 4: Detect Client-Side Authorization Checks - pattern: "if\\s*\\((?:user|currentUser)\\.(?:role|isAdmin|hasPermission|can[A-Z][a-zA-Z]+|is[A-Z][a-zA-Z]+)\\)\\s*\\{[^\\}]*?(?:fetch|axios|\\$\\.ajax|http\\.get|http\\.post)\\([^\\)]*?\\)" message: "Authorization logic implemented on client-side. Client-side authorization checks can be bypassed. Always enforce authorization on the server." - + # Pattern 5: Detect Improper CORS Configuration - pattern: "(?:app\\.use\\(cors\\(\\{[^\\}]*?origin:\\s*['\"]\\*['\"])|Access-Control-Allow-Origin:\\s*['\"]\\*['\"]" message: "Wildcard CORS policy detected. This allows any domain to make cross-origin requests. Restrict CORS to specific trusted domains." - + # Pattern 6: Detect Lack of Role Checks in Admin Functions - pattern: "(?:function|const)\\s+(?:admin|updateUser|deleteUser|createUser|updateRole|manageUsers|setPermission)[^\\{]*?\\{[^\\}]*?\\}" negative_pattern: "(?:role|permission|isAdmin|hasAccess|authorize|authenticate|auth\\.check|checkPermission|checkRole|verifyRole|ensureAdmin|adminOnly|adminRequired|requirePermission)" message: "Administrative function appears to be missing role or permission checks. Implement proper authorization checks to restrict access to administrative functions." - + # Pattern 7: Detect Missing Login Rate Limiting - pattern: "(?:function|const)\\s+(?:login|signin|authenticate|auth)[^\\{]*?\\{[^\\}]*?(?:compare(?:Sync)?|check(?:Password)?|match(?:Password)?|verify(?:Password)?)[^\\}]*?\\}" negative_pattern: "(?:rate(?:Limit)?|throttle|limit|delay|cooldown|attempt|counter|maxTries|maxAttempts|lockout|timeout)" message: "Login function appears to be missing rate limiting. Implement rate limiting to prevent brute force attacks." - + # Pattern 8: Detect Horizontal Privilege Escalation Vulnerability - pattern: "(?:findById|findOne|findByPk|get)\\((?:req|request)\\.(?:params|query|body)\\.(?:id|userId|accountId)\\)" negative_pattern: "(?:!=|!==|===|==)\\s*(?:req\\.user\\.id|req\\.userId|currentUser\\.id|user\\.id|session\\.userId)" message: "Potential horizontal privilege escalation vulnerability. Ensure the requested resource belongs to the authenticated user." - + # Pattern 9: Detect Missing CSRF Protection - pattern: "(?:app|router)\\.(?:post|put|delete|patch)\\(['\"][^'\"]+['\"]" negative_pattern: "(?:csrf|xsrf|csurf|csrfProtection|antiForgery|csrfToken|csrfMiddleware)" message: "Route may be missing CSRF protection. Implement CSRF tokens for state-changing operations to prevent cross-site request forgery attacks." - + # Pattern 10: Detect Bypassing Access Control with Path Traversal - pattern: "(?:fs|require)(?:\\.promises)?\\.(read|open|access|stat)(?:File|Sync)?\\([^\\)]*?(?:req|request)\\.(?:params|query|body|path)\\.[^\\)]*?\\)" negative_pattern: "(?:normalize|resolve|sanitize|validate|pathValidation|checkPath)" message: "Potential path traversal vulnerability in file access. Validate and sanitize user-supplied paths to prevent directory traversal attacks." - + # Pattern 11: Detect Missing Authentication Middleware - pattern: "(?:new\\s+)?express\\(\\)|(?:import|require)\\(['\"]express['\"]\\)" negative_pattern: "(?:app\\.use\\((?:passport|auth|jwt|session|authenticate)|passport\\.authenticate|express-session|express-jwt|jsonwebtoken|requiresAuth|\\bauth\\b)" message: "Express application may be missing authentication middleware. Implement proper authentication to secure your application." - + # Pattern 12: Detect Insecure Cookie Settings - pattern: "(?:res\\.cookie|cookie\\.set|cookies\\.set|document\\.cookie)\\([^\\)]*?\\)" negative_pattern: "(?:secure:\\s*true|httpOnly:\\s*true|sameSite|expires|maxAge)" message: "Cookies appear to be set without security attributes. Set the secure, httpOnly, and sameSite attributes for sensitive cookies." - + # Pattern 13: Detect Hidden Form Fields for Access Control - pattern: "]*?type=['\"]hidden['\"][^>]*?(?:(?:name|id)=['\"](?:admin|role|isAdmin|access|permission|privilege)['\"])" message: "Hidden form fields used for access control. Never rely on hidden form fields for access control decisions as they can be easily manipulated." - + # Pattern 14: Detect Client-Side Access Control Routing - pattern: "(?:isAdmin|hasRole|hasPermission|userCan|canAccess)\\s*\\?\\s*<(?:Route|Navigate|Link|Redirect)" message: "Client-side conditional routing based on user roles detected. Always enforce access control on the server side as client-side checks can be bypassed." - + # Pattern 15: Detect Access Control based on URL Parameters - pattern: "if\\s*\\((?:req|request)\\.(?:query|params)\\.(?:admin|mode|access|role|type)\\s*===?\\s*['\"](?:admin|true|1|superuser|manager)['\"]\\)" message: "Access control based on URL parameters detected. Never use request parameters for access control decisions as they can be easily manipulated." @@ -84,7 +84,7 @@ actions: - type: suggest message: | **JavaScript Access Control Best Practices:** - + 1. **Implement Server-Side Access Control** - Never rely solely on client-side access control - Use middleware to enforce authorization @@ -96,21 +96,21 @@ actions: if (!req.user) { return res.status(401).json({ error: 'Authentication required' }); } - + if (!req.user.roles.includes(role)) { return res.status(403).json({ error: 'Insufficient permissions' }); } - + next(); }; } - + // Usage in routes app.get('/admin/users', requireRole('admin'), (req, res) => { // Handle admin-only route }); ``` - + 2. **Implement Proper Authentication** - Use established authentication libraries - Implement multi-factor authentication for sensitive operations @@ -118,7 +118,7 @@ actions: ```javascript const passport = require('passport'); const JwtStrategy = require('passport-jwt').Strategy; - + passport.use(new JwtStrategy(jwtOptions, async (payload, done) => { try { const user = await User.findById(payload.sub); @@ -130,16 +130,16 @@ actions: return done(error, false); } })); - + // Protect routes - app.get('/protected', + app.get('/protected', passport.authenticate('jwt', { session: false }), (req, res) => { res.json({ success: true }); } ); ``` - + 3. **Implement Proper Authorization** - Use attribute or role-based access control - Check permissions for each protected resource @@ -151,28 +151,28 @@ actions: try { // Get user permissions from database const userPermissions = await getUserPermissions(req.user.id); - + if (!userPermissions.includes(permission)) { return res.status(403).json({ error: 'Permission denied' }); } - + next(); } catch (error) { next(error); } }; } - + // Usage - app.post('/articles', + app.post('/articles', authenticate, - checkPermission('article:create'), + checkPermission('article:create'), (req, res) => { // Create article } ); ``` - + 4. **Protect Against Insecure Direct Object References (IDOR)** - Validate that the requested resource belongs to the user - Use indirect references or access control lists @@ -181,32 +181,32 @@ actions: app.get('/documents/:id', authenticate, async (req, res) => { try { const document = await Document.findById(req.params.id); - + // Check if document exists if (!document) { return res.status(404).json({ error: 'Document not found' }); } - + // Check if user owns the document or has access - if (document.userId !== req.user.id && + if (document.userId !== req.user.id && !(await userHasAccess(req.user.id, document.id))) { return res.status(403).json({ error: 'Access denied' }); } - + res.json(document); } catch (error) { res.status(500).json({ error: error.message }); } }); ``` - + 5. **Implement Proper CORS Configuration** - Never use wildcard (*) in production - Whitelist specific trusted origins - Example: ```javascript const cors = require('cors'); - + const corsOptions = { origin: ['https://trusted-app.com', 'https://admin.trusted-app.com'], methods: ['GET', 'POST', 'PUT', 'DELETE'], @@ -214,31 +214,31 @@ actions: credentials: true, maxAge: 86400 // 24 hours }; - + app.use(cors(corsOptions)); ``` - + 6. **Implement CSRF Protection** - Use anti-CSRF tokens for state-changing operations - Validate the token on the server - Example with csurf: ```javascript const csrf = require('csurf'); - + // Setup CSRF protection const csrfProtection = csrf({ cookie: true }); - + // Generate CSRF token app.get('/form', csrfProtection, (req, res) => { res.render('form', { csrfToken: req.csrfToken() }); }); - + // Validate CSRF token app.post('/process', csrfProtection, (req, res) => { // Process the request }); ``` - + 7. **Implement Secure Cookie Settings** - Set secure, httpOnly, and sameSite attributes - Use appropriate expiration times @@ -253,14 +253,14 @@ actions: domain: 'yourdomain.com' }); ``` - + 8. **Implement Rate Limiting** - Apply rate limiting to authentication endpoints - Prevent brute force attacks - Example with express-rate-limit: ```javascript const rateLimit = require('express-rate-limit'); - + const loginLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 5, // 5 attempts per window @@ -270,19 +270,19 @@ actions: error: 'Too many login attempts, please try again after 15 minutes' } }); - + app.post('/login', loginLimiter, (req, res) => { // Handle login }); ``` - + 9. **Implement Proper Session Management** - Use secure session management libraries - Rotate session IDs after login - Example: ```javascript const session = require('express-session'); - + app.use(session({ secret: process.env.SESSION_SECRET, resave: false, @@ -294,54 +294,54 @@ actions: maxAge: 3600000 // 1 hour } })); - + app.post('/login', (req, res) => { // Authenticate user - + // Regenerate session to prevent session fixation req.session.regenerate((err) => { if (err) { return res.status(500).json({ error: 'Failed to create session' }); } - + // Set authenticated user in session req.session.userId = user.id; req.session.authenticated = true; - + res.json({ success: true }); }); }); ``` - + 10. **Implement Proper Access Control for APIs** - Use OAuth 2.0 or JWT for API authentication - Implement proper scope checking - Example with JWT: ```javascript const jwt = require('jsonwebtoken'); - + function verifyToken(req, res, next) { const token = req.headers.authorization?.split(' ')[1]; - + if (!token) { return res.status(401).json({ error: 'No token provided' }); } - + try { const decoded = jwt.verify(token, process.env.JWT_SECRET); req.user = decoded; - + // Check if token has required scope if (req.route.path === '/api/admin' && !decoded.scopes.includes('admin')) { return res.status(403).json({ error: 'Insufficient scope' }); } - + next(); } catch (error) { return res.status(401).json({ error: 'Invalid token' }); } } - + // Protect API routes app.get('/api/users', verifyToken, (req, res) => { // Handle request @@ -353,19 +353,19 @@ actions: # Check 1: Authentication middleware - pattern: "(?:app\\.use\\((?:authenticate|auth\\.initialize|passport\\.initialize|express-session|jwt))|(?:passport\\.authenticate\\()|(?:auth\\.required)" message: "Authentication middleware is implemented correctly." - + # Check 2: Authorization checks - pattern: "(?:isAuthorized|checkPermission|hasRole|requireRole|checkAccess|canAccess|checkAuth|roleRequired|requireScope)" message: "Authorization checks are implemented." - + # Check 3: CSRF protection - pattern: "(?:csrf|csurf|csrfProtection|antiForgery|csrfToken)" message: "CSRF protection is implemented." - + # Check 4: Secure cookies - pattern: "(?:cookie|cookies).*(?:secure:\\s*true|httpOnly:\\s*true|sameSite)" message: "Secure cookie settings are configured." - + # Check 5: CORS configuration - pattern: "cors\\(\\{[^\\}]*?origin:\\s*\\[[^\\]]+\\]" message: "CORS is configured with specific origins rather than wildcards." @@ -397,4 +397,6 @@ metadata: - "https://nodejs.org/en/security/best-practices/" - "https://expressjs.com/en/advanced/best-practice-security.html" - "https://auth0.com/blog/node-js-and-express-tutorial-building-and-securing-restful-apis/" - +``` + + diff --git a/.cursor/rules/javascript-cryptographic-failures.mdc b/.cursor/rules/javascript-cryptographic-failures.mdc index a02100c..ab88bb5 100644 --- a/.cursor/rules/javascript-cryptographic-failures.mdc +++ b/.cursor/rules/javascript-cryptographic-failures.mdc @@ -4,7 +4,7 @@ globs: **/*.js, **/*.jsx, **/*.ts, **/*.tsx, !**/node_modules/**, !**/dist/**, ! --- # JavaScript Cryptographic Failures (OWASP A02:2021) - +```yaml name: javascript_cryptographic_failures description: Detect and prevent cryptographic failures in JavaScript applications as defined in OWASP Top 10:2021-A02 @@ -14,64 +14,64 @@ actions: # Pattern 1: Weak or insecure cryptographic algorithms - pattern: "(?:createHash|crypto\\.createHash)\\(['\"](?:md5|sha1)['\"]\\)|(?:crypto|require\\(['\"]crypto['\"]\\))\\.(?:createHash|Hash)\\(['\"](?:md5|sha1)['\"]\\)|new (?:MD5|SHA1)\\(|CryptoJS\\.(?:MD5|SHA1)\\(" message: "Using weak hashing algorithms (MD5/SHA1). Use SHA-256 or stronger algorithms." - + # Pattern 2: Hardcoded secrets/credentials - pattern: "(?:const|let|var)\\s+(?:password|secret|key|token|auth|apiKey|api_key)\\s*=\\s*['\"][^'\"]+['\"]" message: "Potential hardcoded credentials detected. Store secrets in environment variables or a secure vault." - + # Pattern 3: Insecure random number generation - pattern: "Math\\.random\\(\\)|Math\\.floor\\(\\s*Math\\.random\\(\\)\\s*\\*" message: "Using Math.random() for security purposes. Use crypto.randomBytes() or Web Crypto API for cryptographic operations." - + # Pattern 4: Weak SSL/TLS configuration - pattern: "(?:tls|https|require\\(['\"]https['\"]\\)|require\\(['\"]tls['\"]\\))\\.(?:createServer|request|get)\\([^\\)]*?{[^}]*?secureProtocol\\s*:\\s*['\"](?:SSLv2_method|SSLv3_method|TLSv1_method|TLSv1_1_method)['\"]" message: "Using deprecated/insecure SSL/TLS protocol versions. Use TLS 1.2+ for secure communications." - + # Pattern 5: Missing certificate validation - pattern: "(?:rejectUnauthorized|strictSSL)\\s*:\\s*false" message: "SSL certificate validation is disabled. Always validate certificates in production environments." - + # Pattern 6: Insecure cipher usage - pattern: "(?:createCipheriv|crypto\\.createCipheriv)\\(['\"](?:des|des3|rc4|bf|blowfish|aes-\\d+-ecb)['\"]" message: "Using insecure encryption cipher or mode. Use AES with GCM or CBC mode with proper padding." - + # Pattern 7: Insufficient key length - pattern: "(?:generateKeyPair|generateKeyPairSync)\\([^,]*?['\"]rsa['\"][^,]*?{[^}]*?modulusLength\\s*:\\s*(\\d{1,3}|1[0-9]{3}|20[0-3][0-9]|204[0-7])\\s*}" 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: "(?:createHash|crypto\\.createHash)\\([^)]*?\\)\\.(?:update|digest)\\([^)]*?\\)|CryptoJS\\.(?:SHA256|SHA512|SHA3)\\([^)]*?\\)" negative_pattern: "(?:bcrypt|scrypt|pbkdf2|argon2)" message: "Using plain hashing for passwords. Use dedicated password hashing functions like bcrypt, scrypt, or PBKDF2." - + # Pattern 9: Missing salt in password hashing - pattern: "(?:pbkdf2|pbkdf2Sync)\\([^,]+,[^,]+,[^,]+,\\s*\\d+\\s*,[^,]+\\)" negative_pattern: "(?:salt|crypto\\.randomBytes)" message: "Ensure you're using a proper random salt with password hashing functions." - + # Pattern 10: Insecure cookie settings - pattern: "(?:document\\.cookie|cookies\\.set|res\\.cookie|cookie\\.serialize)\\([^)]*?\\)" negative_pattern: "(?:secure\\s*:|httpOnly\\s*:|sameSite\\s*:)" message: "Cookies with sensitive data should have secure and httpOnly flags enabled." - + # Pattern 11: Client-side encryption - pattern: "(?:encrypt|decrypt|createCipher|createDecipher)\\([^)]*?\\)" location: "(?:frontend|client|browser|react|vue|angular)" message: "Performing sensitive cryptographic operations on the client side. Move encryption/decryption logic to the server." - + # Pattern 12: Insecure JWT implementation - pattern: "(?:jwt\\.sign|jsonwebtoken\\.sign)\\([^,]*?,[^,]*?,[^\\)]*?\\)" negative_pattern: "(?:expiresIn|algorithm\\s*:\\s*['\"](?:HS256|HS384|HS512|RS256|RS384|RS512|ES256|ES384|ES512)['\"])" message: "JWT implementation missing expiration or using weak algorithm. Set expiresIn and use a strong algorithm." - + # Pattern 13: Weak PRNG in Node.js - pattern: "(?:crypto\\.pseudoRandomBytes|crypto\\.rng|crypto\\.randomInt)\\(" message: "Using potentially weak pseudorandom number generator. Use crypto.randomBytes() for cryptographic security." - + # Pattern 14: Insecure local storage usage for sensitive data - pattern: "(?:localStorage\\.setItem|sessionStorage\\.setItem)\\(['\"](?:token|auth|jwt|password|secret|key|credential)['\"]" message: "Storing sensitive data in browser storage. Use secure HttpOnly cookies for authentication tokens." - + # Pattern 15: Weak password validation - pattern: "(?:password\\.length\\s*>=?\\s*\\d|password\\.match\\(['\"][^'\"]+['\"]\\))" negative_pattern: "(?:password\\.length\\s*>=?\\s*(?:8|9|10|11|12)|[A-Z]|[a-z]|[0-9]|[^A-Za-z0-9])" @@ -80,7 +80,7 @@ actions: - type: suggest message: | **JavaScript Cryptography Best Practices:** - + 1. **Secure Password Storage:** - Use dedicated password hashing algorithms: ```javascript @@ -88,7 +88,7 @@ actions: const bcrypt = require('bcrypt'); const saltRounds = 12; const hashedPassword = await bcrypt.hash(password, saltRounds); - + // Verify password const match = await bcrypt.compare(password, hashedPassword); ``` @@ -96,14 +96,14 @@ actions: ```javascript // Node.js with crypto const crypto = require('crypto'); - + function hashPassword(password) { const salt = crypto.randomBytes(16); const hash = crypto.pbkdf2Sync(password, salt, 310000, 32, 'sha256'); return { salt: salt.toString('hex'), hash: hash.toString('hex') }; } ``` - + 2. **Secure Random Number Generation:** - In Node.js: ```javascript @@ -115,20 +115,20 @@ actions: const array = new Uint8Array(32); window.crypto.getRandomValues(array); ``` - + 3. **Secure Communications:** - Use TLS 1.2+ for all communications: ```javascript // Node.js HTTPS server const https = require('https'); const fs = require('fs'); - + const options = { key: fs.readFileSync('private-key.pem'), cert: fs.readFileSync('certificate.pem'), minVersion: 'TLSv1.2' }; - + https.createServer(options, (req, res) => { res.writeHead(200); res.end('Hello, world!'); @@ -138,7 +138,7 @@ actions: ```javascript // Node.js HTTPS request const https = require('https'); - + const options = { hostname: 'example.com', port: 443, @@ -146,12 +146,12 @@ actions: method: 'GET', rejectUnauthorized: true // Default, but explicitly set for clarity }; - + const req = https.request(options, (res) => { // Handle response }); ``` - + 4. **Proper Key Management:** - Never hardcode secrets in source code - Use environment variables or secure vaults: @@ -161,45 +161,45 @@ actions: const apiKey = process.env.API_KEY; ``` - Consider using dedicated key management services - + 5. **Secure Encryption:** - Use authenticated encryption (AES-GCM): ```javascript // Node.js crypto const crypto = require('crypto'); - + function encrypt(text, masterKey) { const iv = crypto.randomBytes(12); const cipher = crypto.createCipheriv('aes-256-gcm', masterKey, iv); - + let encrypted = cipher.update(text, 'utf8', 'hex'); encrypted += cipher.final('hex'); - + const authTag = cipher.getAuthTag().toString('hex'); - + return { iv: iv.toString('hex'), encrypted, authTag }; } - + function decrypt(encrypted, masterKey) { const decipher = crypto.createDecipheriv( 'aes-256-gcm', masterKey, Buffer.from(encrypted.iv, 'hex') ); - + decipher.setAuthTag(Buffer.from(encrypted.authTag, 'hex')); - + let decrypted = decipher.update(encrypted.encrypted, 'hex', 'utf8'); decrypted += decipher.final('utf8'); - + return decrypted; } ``` - + 6. **Secure Cookie Handling:** - Set secure and httpOnly flags: ```javascript @@ -211,17 +211,17 @@ actions: maxAge: 3600000 // 1 hour }); ``` - + 7. **JWT Security:** - Use strong algorithms and set expiration: ```javascript // Node.js with jsonwebtoken const jwt = require('jsonwebtoken'); - + const token = jwt.sign( { userId: user.id }, process.env.JWT_SECRET, - { + { expiresIn: '1h', algorithm: 'HS256' } @@ -236,22 +236,22 @@ actions: // Handle invalid token } ``` - + 8. **Constant-Time Comparison:** - Use crypto.timingSafeEqual for comparing secrets: ```javascript const crypto = require('crypto'); - + function safeCompare(a, b) { const bufA = Buffer.from(a); const bufB = Buffer.from(b); - + // Ensure the buffers are the same length to avoid timing attacks // based on length differences if (bufA.length !== bufB.length) { return false; } - + return crypto.timingSafeEqual(bufA, bufB); } ``` @@ -261,15 +261,15 @@ actions: # Check 1: Proper password hashing - pattern: "bcrypt\\.hash|scrypt|pbkdf2|argon2" message: "Using secure password hashing algorithm." - + # Check 2: Secure random generation - pattern: "crypto\\.randomBytes|window\\.crypto\\.getRandomValues" message: "Using cryptographically secure random number generation." - + # Check 3: Strong TLS configuration - pattern: "minVersion\\s*:\\s*['\"]TLSv1_2['\"]|minVersion\\s*:\\s*['\"]TLSv1_3['\"]" message: "Using secure TLS configuration." - + # Check 4: Proper certificate validation - pattern: "rejectUnauthorized\\s*:\\s*true|strictSSL\\s*:\\s*true" message: "Properly validating SSL certificates." @@ -301,4 +301,6 @@ metadata: - "https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto" - "https://www.npmjs.com/package/bcrypt" - "https://www.npmjs.com/package/jsonwebtoken" - +``` + + diff --git a/.cursor/rules/javascript-identification-authentication-failures.mdc b/.cursor/rules/javascript-identification-authentication-failures.mdc index a7d3f51..2e0d55e 100644 --- a/.cursor/rules/javascript-identification-authentication-failures.mdc +++ b/.cursor/rules/javascript-identification-authentication-failures.mdc @@ -4,7 +4,7 @@ globs: **/*.js, **/*.jsx, **/*.ts, **/*.tsx, !**/node_modules/**, !**/dist/**, ! --- # JavaScript Identification and Authentication Failures (OWASP A07:2021) - +```yaml name: javascript_identification_authentication_failures description: Detect and prevent identification and authentication failures in JavaScript applications as defined in OWASP Top 10:2021-A07 @@ -14,70 +14,70 @@ actions: # Pattern 1: Weak Password Validation - pattern: "(?:password|passwd|pwd)\\s*\\.\\s*(?:length\\s*[<>]=?\\s*(?:[0-9]|10)\\b|match\\(\\s*['\"][^'\"]*['\"]\\s*\\))" message: "Weak password validation detected. Implement strong password policies requiring minimum length, complexity, and avoiding common passwords." - + # Pattern 2: Missing MFA Implementation - pattern: "(?:login|signin|authenticate|auth)\\s*\\([^)]*\\)\\s*\\{[^}]*?\\}" negative_pattern: "(?:mfa|2fa|two-factor|multi-factor|otp|totp)" message: "Authentication implementation without multi-factor authentication (MFA). Consider implementing MFA for enhanced security." - + # Pattern 3: Hardcoded Credentials - pattern: "(?:const|let|var)\\s+(?:password|passwd|pwd|secret|key|token|apiKey)\\s*=\\s*['\"][^'\"]+['\"]" message: "Hardcoded credentials detected. Store sensitive authentication data in secure configuration or environment variables." - + # Pattern 4: Insecure Session Management - pattern: "(?:localStorage|sessionStorage)\\.setItem\\(['\"](?:token|jwt|session|auth|user)['\"]" message: "Storing authentication tokens in localStorage or sessionStorage. Consider using HttpOnly cookies for sensitive authentication data." - + # Pattern 5: Missing CSRF Protection - pattern: "(?:post|put|delete|patch)\\([^)]*?\\)" negative_pattern: "(?:csrf|xsrf|token)" location: "(?:src|components|pages|api)" message: "Potential missing CSRF protection in API requests. Implement CSRF tokens for state-changing operations." - + # Pattern 6: Insecure JWT Handling - pattern: "jwt\\.sign\\([^)]*?{[^}]*?}\\s*,\\s*[^,)]+\\s*(?:\\)|,\\s*{\\s*(?:expiresIn|algorithm)\\s*:\\s*[^}]*?}\\s*\\))" negative_pattern: "(?:expiresIn|exp).*(?:algorithm|alg)" message: "Insecure JWT configuration. Ensure JWTs have proper expiration and use secure algorithms (RS256 preferred over HS256)." - + # Pattern 7: Insecure Password Storage - pattern: "(?:bcrypt|argon2|pbkdf2|scrypt)\\.[^(]*\\([^)]*?(?:rounds|iterations|cost|factor)\\s*[:<=>]\\s*(?:[0-9]|1[0-2])\\b" message: "Weak password hashing parameters. Use sufficient work factors for password hashing algorithms." - + # Pattern 8: Missing Account Lockout - pattern: "(?:login|signin|authenticate|auth)\\s*\\([^)]*\\)\\s*\\{[^}]*?\\}" negative_pattern: "(?:lock|attempt|count|limit|throttle|rate)" message: "Authentication implementation without account lockout or rate limiting. Implement account lockout after failed attempts." - + # Pattern 9: Insecure Password Recovery - pattern: "(?:reset|forgot|recover)(?:Password|Pwd)\\s*\\([^)]*\\)\\s*\\{[^}]*?\\}" negative_pattern: "(?:expire|timeout|token|verify)" message: "Potentially insecure password recovery mechanism. Implement secure, time-limited recovery tokens." - + # Pattern 10: Missing Brute Force Protection - pattern: "(?:login|signin|authenticate|auth)\\s*\\([^)]*\\)\\s*\\{[^}]*?\\}" negative_pattern: "(?:captcha|recaptcha|hcaptcha|rate\\s*limit)" message: "Authentication without CAPTCHA or rate limiting. Implement protection against brute force attacks." - + # Pattern 11: Insecure Remember Me Functionality - pattern: "(?:rememberMe|keepLoggedIn|staySignedIn)" negative_pattern: "(?:secure|httpOnly|sameSite)" message: "Potentially insecure 'Remember Me' functionality. Implement with secure, HttpOnly cookies and proper expiration." - + # Pattern 12: Insecure Logout Implementation - pattern: "(?:logout|signout)\\s*\\([^)]*\\)\\s*\\{[^}]*?\\}" negative_pattern: "(?:invalidate|revoke|clear|remove).*(?:token|session|cookie)" message: "Potentially incomplete logout implementation. Ensure proper invalidation of sessions and tokens on logout." - + # Pattern 13: Missing Session Timeout - pattern: "(?:session|cookie|jwt)\\s*\\.\\s*(?:create|set|sign)" negative_pattern: "(?:expire|timeout|maxAge)" message: "Missing session timeout configuration. Implement proper session expiration for security." - + # Pattern 14: Insecure OAuth Implementation - pattern: "(?:oauth|openid|oidc).*(?:callback|redirect)" negative_pattern: "(?:state|nonce|pkce)" message: "Potentially insecure OAuth implementation. Use state parameters, PKCE for authorization code flow, and validate redirect URIs." - + # Pattern 15: Missing Credential Validation - pattern: "(?:email|username|user)\\s*=\\s*(?:req\\.body|req\\.query|req\\.params|formData\\.get)\\(['\"][^'\"]+['\"]\\)" negative_pattern: "(?:validate|sanitize|check|trim)" @@ -86,7 +86,7 @@ actions: - type: suggest message: | **JavaScript Identification and Authentication Failures Best Practices:** - + 1. **Strong Password Policies:** - Implement minimum length (at least 12 characters) - Require complexity (uppercase, lowercase, numbers, special characters) @@ -95,24 +95,24 @@ actions: ```javascript // Using a library like zxcvbn for password strength estimation import zxcvbn from 'zxcvbn'; - + function validatePassword(password) { if (password.length < 12) { return { valid: false, message: 'Password must be at least 12 characters' }; } - + const strength = zxcvbn(password); if (strength.score < 3) { - return { - valid: false, - message: 'Password is too weak. ' + strength.feedback.warning + return { + valid: false, + message: 'Password is too weak. ' + strength.feedback.warning }; } - + return { valid: true }; } ``` - + 2. **Multi-Factor Authentication (MFA):** - Implement TOTP (Time-based One-Time Password) - Support hardware security keys (WebAuthn/FIDO2) @@ -120,10 +120,10 @@ actions: ```javascript // Using speakeasy for TOTP implementation import speakeasy from 'speakeasy'; - + // Generate a secret for a user const secret = speakeasy.generateSecret({ length: 20 }); - + // Verify a token function verifyToken(token, secret) { return speakeasy.totp.verify({ @@ -134,7 +134,7 @@ actions: }); } ``` - + 3. **Secure Session Management:** - Use HttpOnly, Secure, and SameSite cookies - Implement proper session expiration @@ -155,27 +155,27 @@ actions: saveUninitialized: false })); ``` - + 4. **CSRF Protection:** - Implement CSRF tokens for all state-changing operations - Example: ```javascript // Using csurf middleware with Express import csrf from 'csurf'; - + // Setup CSRF protection const csrfProtection = csrf({ cookie: true }); - + // Apply to routes app.post('/api/user/profile', csrfProtection, (req, res) => { // Handle the request }); - + // In your frontend (React example) function ProfileForm() { // Get CSRF token from cookie or meta tag const csrfToken = document.querySelector('meta[name="csrf-token"]').content; - + return (
@@ -185,7 +185,7 @@ actions: ); } ``` - + 5. **Secure JWT Implementation:** - Use strong algorithms (RS256 preferred over HS256) - Include proper expiration (exp), issued at (iat), and audience (aud) claims @@ -193,13 +193,13 @@ actions: ```javascript import jwt from 'jsonwebtoken'; import fs from 'fs'; - + // Using asymmetric keys (preferred for production) const privateKey = fs.readFileSync('private.key'); - + function generateToken(userId) { return jwt.sign( - { + { sub: userId, iat: Math.floor(Date.now() / 1000), exp: Math.floor(Date.now() / 1000) + (60 * 60), // 1 hour @@ -210,30 +210,30 @@ actions: ); } ``` - + 6. **Secure Password Storage:** - Use bcrypt, Argon2, or PBKDF2 with sufficient work factor - Example: ```javascript import bcrypt from 'bcrypt'; - + async function hashPassword(password) { // Cost factor of 12+ for production const saltRounds = 12; return await bcrypt.hash(password, saltRounds); } - + async function verifyPassword(password, hash) { return await bcrypt.compare(password, hash); } ``` - + 7. **Account Lockout and Rate Limiting:** - Implement progressive delays or account lockout after failed attempts - Example: ```javascript import rateLimit from 'express-rate-limit'; - + // Apply rate limiting to login endpoint const loginLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes @@ -242,31 +242,31 @@ actions: standardHeaders: true, legacyHeaders: false, }); - + app.post('/api/login', loginLimiter, (req, res) => { // Handle login }); ``` - + 8. **Secure Password Recovery:** - Use time-limited, single-use tokens - Send to verified email addresses only - Example: ```javascript import crypto from 'crypto'; - + function generatePasswordResetToken() { return { token: crypto.randomBytes(32).toString('hex'), expires: new Date(Date.now() + 3600000) // 1 hour }; } - + // Store token in database with user ID and expiration // Send token via email (never include in URL directly) // Verify token is valid and not expired when used ``` - + 9. **Brute Force Protection:** - Implement CAPTCHA or reCAPTCHA - Example: @@ -278,22 +278,22 @@ actions: headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: `secret=${process.env.RECAPTCHA_SECRET_KEY}&response=${token}` }); - + const data = await response.json(); return data.success && data.score >= 0.5; // Adjust threshold as needed } - + app.post('/api/login', async (req, res) => { const { recaptchaToken } = req.body; - + if (!(await verifyRecaptcha(recaptchaToken))) { return res.status(400).json({ error: 'CAPTCHA verification failed' }); } - + // Continue with login process }); ``` - + 10. **Secure Logout Implementation:** - Invalidate sessions on both client and server - Example: @@ -304,7 +304,7 @@ actions: if (err) { return res.status(500).json({ error: 'Failed to logout' }); } - + // Clear client-side cookie res.clearCookie('__Host-session', { httpOnly: true, @@ -312,12 +312,12 @@ actions: sameSite: 'strict', path: '/' }); - + res.status(200).json({ message: 'Logged out successfully' }); }); }); ``` - + 11. **Secure OAuth Implementation:** - Use state parameter to prevent CSRF - Implement PKCE for authorization code flow @@ -328,52 +328,52 @@ actions: function generateOAuthState() { return crypto.randomBytes(32).toString('hex'); } - + function generateCodeVerifier() { return crypto.randomBytes(43).toString('base64url'); } - + function generateCodeChallenge(verifier) { const hash = crypto.createHash('sha256').update(verifier).digest('base64url'); return hash; } - + // Store state and code verifier in session // Use code challenge in authorization request // Verify state and use code verifier in token request ``` - + 12. **Input Validation:** - Validate and sanitize all user inputs - Example: ```javascript import validator from 'validator'; - + function validateCredentials(email, password) { const errors = {}; - + if (!validator.isEmail(email)) { errors.email = 'Invalid email format'; } - + if (!password || password.length < 12) { errors.password = 'Password must be at least 12 characters'; } - + return { isValid: Object.keys(errors).length === 0, errors }; } ``` - + 13. **Secure Headers:** - Implement security headers for authentication-related pages - Example: ```javascript // Using helmet with Express import helmet from 'helmet'; - + app.use(helmet({ contentSecurityPolicy: { directives: { @@ -387,7 +387,7 @@ actions: referrerPolicy: { policy: 'same-origin' } })); ``` - + 14. **Credential Stuffing Protection:** - Implement device fingerprinting and anomaly detection - Example: @@ -400,14 +400,14 @@ actions: acceptLanguage: req.headers['accept-language'] }; } - + // Check if login is from a new device async function isNewDevice(userId, fingerprint) { // Compare with stored fingerprints for this user // Alert or require additional verification for new devices } ``` - + 15. **Secure Password Change:** - Require current password verification - Example: @@ -415,26 +415,26 @@ actions: async function changePassword(userId, currentPassword, newPassword) { // Retrieve user from database const user = await getUserById(userId); - + // Verify current password const isValid = await bcrypt.compare(currentPassword, user.passwordHash); if (!isValid) { return { success: false, message: 'Current password is incorrect' }; } - + // Validate new password strength const validation = validatePassword(newPassword); if (!validation.valid) { return { success: false, message: validation.message }; } - + // Hash and store new password const newHash = await bcrypt.hash(newPassword, 12); await updateUserPassword(userId, newHash); - + // Invalidate existing sessions (optional but recommended) await invalidateUserSessions(userId); - + return { success: true }; } ``` @@ -444,19 +444,19 @@ actions: # Check 1: Strong Password Validation - pattern: "(?:password|pwd).*(?:length\\s*>=\\s*(?:1[2-9]|[2-9][0-9]))" message: "Implementing strong password length requirements (12+ characters)." - + # Check 2: Secure Password Storage - pattern: "(?:bcrypt|argon2|pbkdf2|scrypt)\\.[^(]*\\([^)]*?(?:rounds|iterations|cost|factor)\\s*[:<=>]\\s*(?:1[2-9]|[2-9][0-9])" message: "Using secure password hashing with appropriate work factor." - + # Check 3: CSRF Protection - pattern: "(?:csrf|xsrf).*(?:token|middleware|protection)" message: "Implementing CSRF protection for state-changing operations." - + # Check 4: Secure Cookie Configuration - pattern: "(?:cookie|session).*(?:httpOnly|secure|sameSite)" message: "Using secure cookie configuration for sessions." - + # Check 5: Rate Limiting - pattern: "(?:rate|limit|throttle).*(?:login|signin|auth)" message: "Implementing rate limiting for authentication endpoints." @@ -490,4 +490,6 @@ metadata: - "https://auth0.com/blog/a-look-at-the-latest-draft-for-jwt-bcp/" - "https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Multifactor_Authentication_Cheat_Sheet.md" - "https://www.nist.gov/itl/applied-cybersecurity/tig/back-basics-multi-factor-authentication" - +``` + + diff --git a/.cursor/rules/javascript-injection.mdc b/.cursor/rules/javascript-injection.mdc index 00e33cc..d3ce1bd 100644 --- a/.cursor/rules/javascript-injection.mdc +++ b/.cursor/rules/javascript-injection.mdc @@ -4,7 +4,7 @@ globs: **/*.js, **/*.jsx, **/*.ts, **/*.tsx, !**/node_modules/**, !**/dist/**, ! --- # JavaScript Injection Security Rule - +```yaml name: javascript_injection description: Identifies and helps prevent injection vulnerabilities in JavaScript applications, as defined in OWASP Top 10:2021-A03. @@ -15,13 +15,13 @@ actions: severity: "critical" message: | 🔴 CRITICAL: Potential code injection vulnerability detected. - + Impact: Attackers can execute arbitrary code in your application context. CWE Reference: CWE-95 (Improper Neutralization of Directives in Dynamically Evaluated Code) - + ❌ Insecure: eval(req.body.data) - + ✅ Secure Alternative: // Use safer alternatives like JSON.parse for JSON data try { @@ -31,102 +31,102 @@ actions: // Handle parsing errors } learn_more_url: "https://owasp.org/www-community/attacks/Direct_Dynamic_Code_Evaluation_Eval_Injection" - + - pattern: "\\$\\(\\s*(['\"])<[^>]+>\\1\\s*\\)" severity: "high" message: | 🟠 HIGH: jQuery HTML injection vulnerability detected. - + Impact: This can lead to Cross-Site Scripting (XSS) attacks. CWE Reference: CWE-79 (Improper Neutralization of Input During Web Page Generation) - + ❌ Insecure: $("
" + userProvidedData + "
") - + ✅ Secure Alternative: // Create element safely, then set text content const div = $("
"); div.text(userProvidedData); learn_more_url: "https://cheatsheetseries.owasp.org/cheatsheets/jQuery_Security_Cheat_Sheet.html" - + - pattern: "document\\.write\\(|document\\.writeln\\(" severity: "high" message: | 🟠 HIGH: Potential DOM-based XSS vulnerability. - + Impact: Attackers can inject malicious HTML/JavaScript into your page. CWE Reference: CWE-79 (Improper Neutralization of Input During Web Page Generation) - + ❌ Insecure: document.write("

" + userGeneratedContent + "

"); - + ✅ Secure Alternative: // Use safer DOM manipulation methods const h1 = document.createElement("h1"); h1.textContent = userGeneratedContent; document.body.appendChild(h1); learn_more_url: "https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html" - + - pattern: "innerHTML\\s*=|outerHTML\\s*=" pattern_negate: "sanitize|DOMPurify|escapeHTML" severity: "high" message: | 🟠 HIGH: Potential DOM-based XSS through innerHTML/outerHTML. - + Impact: Setting HTML content directly can allow script injection. CWE Reference: CWE-79 (Improper Neutralization of Input During Web Page Generation) - + ❌ Insecure: element.innerHTML = userProvidedData; - + ✅ Secure Alternative: // Option 1: Use textContent instead for text element.textContent = userProvidedData; - + // Option 2: Sanitize if HTML is required import DOMPurify from 'dompurify'; element.innerHTML = DOMPurify.sanitize(userProvidedData); learn_more_url: "https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html" - + - pattern: "\\$\\(.*\\)\\.html\\(" pattern_negate: "sanitize|DOMPurify|escapeHTML" severity: "high" message: | 🟠 HIGH: jQuery HTML injection risk detected. - + Impact: Setting HTML content can lead to XSS vulnerabilities. CWE Reference: CWE-79 (Improper Neutralization of Input During Web Page Generation) - + ❌ Insecure: $("#element").html(userProvidedData); - + ✅ Secure Alternative: // Option 1: Use text() instead for text $("#element").text(userProvidedData); - + // Option 2: Sanitize if HTML is required import DOMPurify from 'dompurify'; $("#element").html(DOMPurify.sanitize(userProvidedData)); learn_more_url: "https://cheatsheetseries.owasp.org/cheatsheets/jQuery_Security_Cheat_Sheet.html" - + - pattern: "require\\(([^)]*(req|request|query|param|user|input)[^)]*)\\)" severity: "critical" message: | 🔴 CRITICAL: Dynamic require() can lead to remote code execution. - + Impact: Attackers can load arbitrary modules or access sensitive files. CWE Reference: CWE-95 (Improper Neutralization of Directives in Dynamically Evaluated Code) - + ❌ Insecure: const module = require(req.query.module); - + ✅ Secure Alternative: // Use a whitelisproach const allowedModules = { 'user': './modules/user', 'product': './modules/product' }; - + const moduleName = req.query.module; if (allowedModules[moduleName]) { const module = require(allowedModules[moduleName]); @@ -135,28 +135,28 @@ actions: // Handle invalid module request } learn_more_url: "https://owasp.org/www-project-top-ten/2017/A1_2017-Injection" - + - pattern: "exec\\(([^)]*(req|request|query|param|user|input)[^)]*)\\)" severity: "critical" message: | 🔴 CRITICAL: Command injection vulnerability detected. - + Impact: Attackers can execute arbitrary system commands. CWE Reference: CWE-78 (Improper Neutralization of Special Elements used in an OS Command) - + ❌ Insecure: exec('ls ' + userInput, (error, stdout, stderr) => { // Process output }); - + ✅ Secure Alternative: // Use child_process.execFile with separate arguments import { execFile } from 'child_process'; - + execFile('ls', [safeDirectory], (error, stdout, stderr) => { // Process output safely }); - + // Or use a validation library to sanitize inputs import validator from 'validator'; if (validator.isAlphanumeric(userInput)) { @@ -169,33 +169,33 @@ actions: - type: suggest message: | **JavaScript Injection Prevention Best Practices:** - + 1. **Input Validation:** - Validate all user inputs both client-side and server-side - Use allowlists instead of blocklists - Apply strict type checking and schema validation - + 2. **Output Encoding:** - Always encode/escape output in the correct context (HTML, JavaScript, CSS, URL) - Use libraries like DOMPurify for HTML sanitization - Avoid building HTML, JavaScript, SQL dynamically from user inputs - + 3. **Content Security Policy (CSP):** - Implement a strict CSP to prevent execution of malicious scripts - Use nonce-based or hash-based CSP to allow only specific scripts - + 4. **Structured Data Formats:** - Use structured data formats like JSON, XML with proper parsers - Avoid manually parsing or constructing these formats - + 5. **Parameterized APIs:** - Use parameterized APIs for database queries, OS commands - Separate code from data to prevent injection - + 6. **DOM Manipulation:** - Prefer .textContent over .innerHTML when displaying user content - Use document.createElement() and node methods instead of directly setting HTML - + 7. **Frameworks and Libraries:** - Keep frameworks and libraries updated to latest secure versions - Many modern frameworks offer built-in protections against common injection attacks @@ -203,7 +203,7 @@ actions: metadata: priority: critical version: 1.1 - tags: + tags: - language:javascript - category:security - standard:owasp-top10 @@ -213,4 +213,5 @@ metadata: - "https://cheatsheetseries.owasp.org/cheatsheets/Injection_Prevention_Cheat_Sheet.html" - "https://nodegoat.herokuapp.com/tutorial/a1" - "https://github.com/OWASP/NodeGoat" -
+``` + diff --git a/.cursor/rules/javascript-insecure-design.mdc b/.cursor/rules/javascript-insecure-design.mdc index 2a1ccb4..f44ccd6 100644 --- a/.cursor/rules/javascript-insecure-design.mdc +++ b/.cursor/rules/javascript-insecure-design.mdc @@ -4,7 +4,7 @@ globs: **/*.js, **/*.jsx, **/*.ts, **/*.tsx, !**/node_modules/**, !**/dist/**, ! --- # JavaScript Insecure Design (OWASP A04:2021) - +```yaml name: javascript_insecure_design description: Detect and prevent insecure design patterns in JavaScript applications as defined in OWASP Top 10:2021-A04 @@ -15,68 +15,68 @@ actions: - pattern: "app\\.(?:get|post|put|delete|patch)\\([^)]*?\\)\\s*(?!.*(?:rateLimiter|limiter|throttle|rateLimit))" location: "(?:routes|api|controllers)" message: "Potential lack of rate limiting in API endpoint. Consider implementing rate limiting to prevent abuse." - + # Pattern 2: Insecure Direct Object Reference (IDOR) - pattern: "(?:findById|getById|findOne)\\([^)]*?(?:req\\.|request\\.|params\\.|query\\.|body\\.|user\\.|input\\.|form\\.)[^)]*?\\)\\s*(?!.*(?:authorization|permission|access|canAccess|isAuthorized|checkPermission))" location: "(?:routes|api|controllers)" message: "Potential Insecure Direct Object Reference (IDOR) vulnerability. Implement proper authorization checks before accessing objects by ID." - + # Pattern 3: Lack of Input Validation - pattern: "(?:req\\.|request\\.|params\\.|query\\.|body\\.|user\\.|input\\.|form\\.)[a-zA-Z0-9_]+\\s*(?!.*(?:validate|sanitize|check|schema|joi|yup|zod|validator|isValid))" location: "(?:routes|api|controllers)" message: "Potential lack of input validation. Implement proper validation for all user inputs." - + # Pattern 4: Hardcoded Business Logic - pattern: "if\\s*\\([^)]*?(?:role\\s*===\\s*['\"]admin['\"]|isAdmin\\s*===\\s*true|user\\.role\\s*===\\s*['\"]admin['\"])\\s*\\)" message: "Hardcoded business logic for authorization. Consider using a more flexible role-based access control system." - + # Pattern 5: Lack of Proper Error Handling - pattern: "catch\\s*\\([^)]*?\\)\\s*\\{[^}]*?(?:console\\.(?:log|error))[^}]*?\\}" negative_pattern: "(?:res\\.status|next\\(err|next\\(error|errorHandler)" message: "Improper error handling. Avoid only logging errors without proper handling or user feedback." - + # Pattern 6: Insecure Authentication Design - pattern: "(?:password|token|secret|key)\\s*===\\s*(?:req\\.|request\\.|params\\.|query\\.|body\\.|user\\.|input\\.|form\\.)" message: "Insecure authentication design. Avoid direct string comparison for passwords or tokens." - + # Pattern 7: Lack of Proper Logging - pattern: "app\\.(?:get|post|put|delete|patch)\\([^)]*?\\)\\s*(?!.*(?:log|logger|winston|bunyan|morgan|audit))" location: "(?:routes|api|controllers)" message: "Lack of proper logging in API endpoint. Implement logging for security-relevant events." - + # Pattern 8: Insecure Defaults - pattern: "new\\s+(?:Session|Cookie|JWT)\\([^)]*?\\{[^}]*?(?:secure\\s*:\\s*false|httpOnly\\s*:\\s*false|sameSite\\s*:\\s*['\"]none['\"])" message: "Insecure default configuration. Avoid setting secure:false, httpOnly:false, or sameSite:'none' for cookies or sessions." - + # Pattern 9: Lack of Proper Access Control - pattern: "router\\.(?:get|post|put|delete|patch)\\([^)]*?\\)\\s*(?!.*(?:authenticate|authorize|requireAuth|isAuthenticated|checkAuth|verifyToken|passport\\.authenticate))" location: "(?:routes|api|controllers)" message: "Potential lack of access control in route definition. Implement proper authentication and authorization middleware." - + # Pattern 10: Insecure File Operations - pattern: "(?:fs\\.(?:readFile|writeFile|appendFile|readdir|stat|access|open|unlink)|require)\\([^)]*?(?:(?:\\+|\\$\\{|\\`)[^)]*?(?:__dirname|__filename|process\\.cwd\\(\\)|path\\.(?:resolve|join)))" negative_pattern: "path\\.normalize|path\\.resolve|path\\.join" message: "Insecure file operations. Use path.normalize() and validate file paths to prevent directory traversal attacks." - + # Pattern 11: Lack of Proper Secrets Management - pattern: "(?:apiKey|secret|password|token|credentials)\\s*=\\s*(?:process\\.env\\.[A-Z_]+|config\\.[a-zA-Z0-9_]+|['\"][^'\"]+['\"])" negative_pattern: "(?:vault|secretsManager|keyVault|secretClient)" message: "Insecure secrets management. Consider using a dedicated secrets management solution instead of environment variables or configuration files." - + # Pattern 12: Insecure Randomness - pattern: "Math\\.random\\(\\)" location: "(?:auth|security|token|password|key|iv|nonce|salt)" message: "Insecure randomness. Use crypto.randomBytes() or a similar cryptographically secure random number generator for security-sensitive operations." - + # Pattern 13: Lack of Proper Input Sanitization for Templates - pattern: "(?:template|render|compile|ejs\\.render|handlebars\\.compile|pug\\.render)\\([^)]*?(?:(?:\\+|\\$\\{|\\`)[^)]*?(?:req\\.|request\\.|params\\.|query\\.|body\\.|user\\.|input\\.|form\\.))" message: "Potential template injection vulnerability. Sanitize user input before using in templates." - + # Pattern 14: Insecure WebSocket Implementation - pattern: "new\\s+WebSocket\\([^)]*?\\)|io\\.on\\(['\"]connection['\"]" negative_pattern: "(?:authenticate|authorize|verifyClient|beforeConnect)" message: "Potentially insecure WebSocket implementation. Implement proper authentication and authorization for WebSocket connections." - + # Pattern 15: Insecure Cross-Origin Resource Sharing (CORS) - pattern: "(?:cors\\(\\{[^}]*?origin\\s*:\\s*['\"]\\*['\"]|app\\.use\\(cors\\(\\{[^}]*?origin\\s*:\\s*['\"]\\*['\"])" message: "Insecure CORS configuration. Avoid using wildcard (*) for CORS origin in production environments." @@ -84,7 +84,7 @@ actions: - type: suggest message: | **JavaScript Secure Design Best Practices:** - + 1. **Defense in Depth Strategy:** - Implement multiple layers of security controls - Don't rely on a single security mechanism @@ -97,7 +97,7 @@ actions: app.use(express.json({ limit: '10kb' })); // Request size limiting app.use(sanitize()); // Input sanitization ``` - + 2. **Proper Access Control:** - Implement role-based access control (RBAC) - Use middleware for authorization checks @@ -109,30 +109,30 @@ actions: if (!req.user) { return res.status(401).json({ error: 'Unauthorized' }); } - + if (req.user.role !== role) { return res.status(403).json({ error: 'Forbidden' }); } - + next(); }; }; - + // Apply to routes - router.get('/admin/users', - authenticate, - requireRole('admin'), + router.get('/admin/users', + authenticate, + requireRole('admin'), adminController.listUsers ); ``` - + 3. **Rate Limiting:** - Implement rate limiting for all API endpoints - Use different limits for different endpoints based on sensitivity - Example: ```javascript const rateLimit = require('express-rate-limit'); - + // General API rate limit const apiLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes @@ -140,7 +140,7 @@ actions: standardHeaders: true, legacyHeaders: false, }); - + // More strict limit for authentication endpoints const authLimiter = rateLimit({ windowMs: 15 * 60 * 1000, @@ -148,19 +148,19 @@ actions: standardHeaders: true, legacyHeaders: false, }); - + // Apply rate limiters app.use('/api/', apiLimiter); app.use('/api/auth/', authLimiter); ``` - + 4. **Input Validation:** - Validate all user inputs using schema validation - Implement both client and server-side validation - Example: ```javascript const Joi = require('joi'); - + // Define validation schema const userSchema = Joi.object({ username: Joi.string().alphanum().min(3).max(30).required(), @@ -168,7 +168,7 @@ actions: password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{8,30}$')).required(), role: Joi.string().valid('user', 'admin').default('user') }); - + // Validation middleware const validateUser = (req, res, next) => { const { error } = userSchema.validate(req.body); @@ -177,11 +177,11 @@ actions: } next(); }; - + // Apply validation router.post('/users', validateUser, userController.create); ``` - + 5. **Proper Error Handling:** - Implement centralized error handling - Avoid exposing sensitive information in error messages @@ -191,7 +191,7 @@ actions: app.use((err, req, res, next) => { // Log error for internal use console.error(err.stack); - + // Send appropriate response to client const statusCode = err.statusCode || 500; res.status(statusCode).json({ @@ -199,7 +199,7 @@ actions: message: statusCode === 500 ? 'Internal server error' : err.message }); }); - + // Custom error class class AppError extends Error { constructor(message, statusCode) { @@ -207,17 +207,17 @@ actions: this.statusCode = statusCode; this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error'; this.isOperational = true; - + Error.captureStackTrace(this, this.constructor); } } - + // Usage in controllers if (!user) { return next(new AppError('User not found', 404)); } ``` - + 6. **Secure Authentication Design:** - Use secure password hashing (bcrypt, Argon2) - Implement proper session management @@ -226,18 +226,18 @@ actions: ```javascript const bcrypt = require('bcrypt'); const jwt = require('jsonwebtoken'); - + // Password hashing const hashPassword = async (password) => { const salt = await bcrypt.genSalt(12); return bcrypt.hash(password, salt); }; - + // Password verification const verifyPassword = async (password, hashedPassword) => { return await bcrypt.compare(password, hashedPassword); }; - + // Token generation const generateToken = (userId) => { return jwt.sign( @@ -246,15 +246,15 @@ actions: { expiresIn: '1h' } ); }; - + // Token verification middleware const verifyToken = (req, res, next) => { const token = req.headers.authorization?.split(' ')[1]; - + if (!token) { return res.status(401).json({ error: 'No token provided' }); } - + try { const decoded = jwt.verify(token, process.env.JWT_SECRET); req.userId = decoded.id; @@ -264,7 +264,7 @@ actions: } }; ``` - + 7. **Comprehensive Logging:** - Log security-relevant events - Include necessary context but avoid sensitive data @@ -272,7 +272,7 @@ actions: - Example: ```javascript const winston = require('winston'); - + // Create logger const logger = winston.createLogger({ level: 'info', @@ -283,11 +283,11 @@ actions: new winston.transports.File({ filename: 'combined.log' }) ] }); - + // Logging middleware app.use((req, res, next) => { const start = Date.now(); - + res.on('finish', () => { const duration = Date.now() - start; logger.info({ @@ -299,10 +299,10 @@ actions: userId: req.user?.id || 'anonymous' }); }); - + next(); }); - + // Security event logging logger.warn({ event: 'failed_login', @@ -311,14 +311,14 @@ actions: timestamp: new Date().toISOString() }); ``` - + 8. **Secure Configuration Management:** - Use environment-specific configurations - Validate configuration at startup - Example: ```javascript const Joi = require('joi'); - + // Define environment variables schema const envSchema = Joi.object({ NODE_ENV: Joi.string().valid('development', 'production', 'test').required(), @@ -328,14 +328,14 @@ actions: JWT_EXPIRES_IN: Joi.string().default('1h'), CORS_ORIGIN: Joi.string().required() }).unknown(); - + // Validate environment variables const { error, value } = envSchema.validate(process.env); - + if (error) { throw new Error(`Configuration validation error: ${error.message}`); } - + // Use validated config const config = { env: value.NODE_ENV, @@ -351,10 +351,10 @@ actions: origin: value.CORS_ORIGIN.split(',') } }; - + module.exports = config; ``` - + 9. **Secure File Operations:** - Validate and sanitize file paths - Use content-type validation for uploads @@ -363,24 +363,24 @@ actions: ```javascript const path = require('path'); const fs = require('fs'); - + // Secure file access function const getSecureFilePath = (userInput) => { // Define allowed directory const baseDir = path.resolve(__dirname, '../public/files'); - + // Normalize and resolve full path const normalizedPath = path.normalize(userInput); const fullPath = path.join(baseDir, normalizedPath); - + // Ensure path is within allowed directory if (!fullPath.startsWith(baseDir)) { throw new Error('Invalid file path'); } - + return fullPath; }; - + // Usage try { const filePath = getSecureFilePath(req.params.filename); @@ -390,7 +390,7 @@ actions: next(error); } ``` - + 10. **Secure WebSocket Implementation:** - Implement authentication for WebSocket connections - Validate and sanitize WebSocket messages @@ -399,18 +399,18 @@ actions: const http = require('http'); const socketIo = require('socket.io'); const jwt = require('jsonwebtoken'); - + const server = http.createServer(app); const io = socketIo(server); - + // WebSocket authentication middleware io.use((socket, next) => { const token = socket.handshake.auth.token; - + if (!token) { return next(new Error('Authentication error')); } - + try { const decoded = jwt.verify(token, process.env.JWT_SECRET); socket.userId = decoded.id; @@ -419,20 +419,20 @@ actions: return next(new Error('Authentication error')); } }); - + io.on('connection', (socket) => { console.log(`User ${socket.userId} connected`); - + // Join user to their own room for private messages socket.join(`user:${socket.userId}`); - + // Message validation socket.on('message', (data) => { // Validate message data if (!data || !data.content || typeof data.content !== 'string') { return socket.emit('error', { message: 'Invalid message format' }); } - + // Process message // ... }); @@ -444,19 +444,19 @@ actions: # Check 1: Rate limiting implementation - pattern: "(?:rateLimit|rateLimiter|limiter|throttle)\\([^)]*?\\)" message: "Implementing rate limiting for API protection." - + # Check 2: Input validation - pattern: "(?:validate|sanitize|check|schema|joi|yup|zod|validator|isValid)" message: "Using input validation or schema validation." - + # Check 3: Proper error handling - pattern: "(?:try\\s*\\{[^}]*?\\}\\s*catch\\s*\\([^)]*?\\)\\s*\\{[^}]*?(?:res\\.status|next\\(err|next\\(error|errorHandler))" message: "Implementing proper error handling." - + # Check 4: Authentication middleware - pattern: "(?:authenticate|authorize|requireAuth|isAuthenticated|checkAuth|verifyToken|passport\\.authenticate)" message: "Using authentication middleware for routes." - + # Check 5: Secure configuration - pattern: "(?:helmet|cors\\(\\{[^}]*?origin\\s*:\\s*(?!['\"]*\\*)['\"])" message: "Using secure HTTP headers and CORS configuration." @@ -488,4 +488,6 @@ metadata: - "https://cheatsheetseries.owasp.org/cheatsheets/Access_Control_Cheat_Sheet.html" - "https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html" - "https://github.com/OWASP/NodeGoat" - +``` + + diff --git a/.cursor/rules/javascript-performance.mdc b/.cursor/rules/javascript-performance.mdc index 059ccc4..b208f23 100644 --- a/.cursor/rules/javascript-performance.mdc +++ b/.cursor/rules/javascript-performance.mdc @@ -4,7 +4,7 @@ globs: *.js, *.ts --- # JavaScript Performance Optimization - +```yaml name: javascript_performance_optimization description: Enforce best practices for optimizing JavaScript performance. @@ -30,4 +30,5 @@ actions: metadata: priority: high version: 1.0 - +``` + diff --git a/.cursor/rules/javascript-security-logging-monitoring-failures.mdc b/.cursor/rules/javascript-security-logging-monitoring-failures.mdc index 8fc33ed..cca7123 100644 --- a/.cursor/rules/javascript-security-logging-monitoring-failures.mdc +++ b/.cursor/rules/javascript-security-logging-monitoring-failures.mdc @@ -4,7 +4,7 @@ globs: **/*.js, **/*.jsx, **/*.ts, **/*.tsx, !**/node_modules/**, !**/dist/**, ! --- # JavaScript Security Logging and Monitoring Failures (OWASP A09:2021) - +```yaml name: javascript_security_logging_monitoring_failures description: Detect and prevent security logging and monitoring failures in JavaScript applications as defined in OWASP Top 10:2021-A09 @@ -14,74 +14,74 @@ actions: # Pattern 1: Missing Error Logging - pattern: "(?:try\\s*{[^}]*}\\s*catch\\s*\\([^)]*\\)\\s*{[^}]*})(?![^;{]*(?:console\\.(?:error|warn|log)|logger?\\.(?:error|warn|log)|captureException))" message: "Error caught without proper logging. Implement structured error logging for security events." - + # Pattern 2: Sensitive Data in Logs - pattern: "console\\.(?:log|warn|error|info|debug)\\s*\\([^)]*(?:password|token|secret|key|credential|auth|jwt|session|cookie)" negative_pattern: "\\*\\*\\*|redact|mask|sanitize" message: "Potential sensitive data in logs. Ensure sensitive information is redacted before logging." - + # Pattern 3: Missing Authentication Logging - pattern: "(?:login|signin|authenticate|auth)\\s*\\([^)]*\\)\\s*{[^}]*}" negative_pattern: "(?:log|audit|record|track)\\s*\\(" message: "Authentication function without logging. Log authentication attempts, successes, and failures." - + # Pattern 4: Missing Authorization Logging - pattern: "(?:authorize|checkPermission|hasAccess|isAuthorized|can)\\s*\\([^)]*\\)\\s*{[^}]*}" negative_pattern: "(?:log|audit|record|track)\\s*\\(" message: "Authorization check without logging. Log access control decisions, especially denials." - + # Pattern 5: Insufficient Error Detail - pattern: "(?:console\\.error|logger?\\.error)\\s*\\([^)]*(?:error|err|exception)\\s*\\)" negative_pattern: "(?:error\\.(?:message|stack|code|name)|JSON\\.stringify\\(error\\)|serialize)" message: "Error logging with insufficient detail. Include error type, message, stack trace, and context." - + # Pattern 6: Missing Security Event Logging - pattern: "(?:bruteForce|rateLimit|block|blacklist|suspicious|anomaly|threat|attack|intrusion|malicious)" negative_pattern: "(?:log|audit|record|track|monitor|alert|notify)" message: "Security event detection without logging. Implement logging for all security-relevant events." - + # Pattern 7: Inconsistent Log Formats - pattern: "console\\.(?:log|warn|error|info|debug)\\s*\\(" negative_pattern: "JSON\\.stringify|structured|format" message: "Inconsistent log format. Use structured logging with consistent formats for easier analysis." - + # Pattern 8: Missing Log Correlation ID - pattern: "(?:api|http|fetch|axios|request)\\s*\\([^)]*\\)" negative_pattern: "(?:correlationId|requestId|traceId|spanId|context)" message: "API request without correlation ID. Include correlation IDs in logs for request tracing." - + # Pattern 9: Missing High-Value Transaction Logging - pattern: "(?:payment|transaction|order|purchase|transfer|withdraw|deposit)\\s*\\([^)]*\\)" negative_pattern: "(?:log|audit|record|track)" message: "High-value transaction without audit logging. Implement comprehensive logging for all transactions." - + # Pattern 10: Client-Side Logging Issues - pattern: "(?:window\\.onerror|window\\.addEventListener\\s*\\(\\s*['\"]error['\"])" negative_pattern: "(?:send|report|log|capture|track)" message: "Client-side error handler without reporting. Implement error reporting to backend services." - + # Pattern 11: Missing Log Levels - pattern: "console\\.log\\s*\\(" negative_pattern: "logger?\\.(?:error|warn|info|debug|trace)" message: "Using console.log without proper log levels. Implement a logging library with appropriate log levels." - + # Pattern 12: Missing Monitoring Integration - pattern: "package\\.json" negative_pattern: "(?:sentry|newrelic|datadog|appinsights|loggly|splunk|elasticsearch|winston|bunyan|pino|loglevel)" file_pattern: "package\\.json$" message: "No logging or monitoring dependencies detected. Consider adding a proper logging library and monitoring integration." - + # Pattern 13: Missing Log Aggregation - pattern: "(?:docker-compose\\.ya?ml|\\.env|\\.env\\.example|Dockerfile)" negative_pattern: "(?:sentry|newrelic|datadog|appinsights|loggly|splunk|elasticsearch|logstash|fluentd|kibana)" file_pattern: "(?:docker-compose\\.ya?ml|\\.env|\\.env\\.example|Dockerfile)$" message: "No log aggregation service configured. Implement centralized log collection and analysis." - + # Pattern 14: Missing Health Checks - pattern: "(?:express|koa|fastify|hapi|http\\.createServer)" negative_pattern: "(?:health|status|heartbeat|alive|ready)" message: "Server without health check endpoint. Implement health checks for monitoring service status." - + # Pattern 15: Missing Rate Limiting Logs - pattern: "(?:rateLimit|throttle|limiter)" negative_pattern: "(?:log|record|track|monitor|alert|notify)" @@ -90,7 +90,7 @@ actions: - type: suggest message: | **JavaScript Security Logging and Monitoring Best Practices:** - + 1. **Structured Error Logging:** - Use structured logging formats (JSON) - Include contextual information with errors @@ -114,7 +114,7 @@ actions: // Handle the error appropriately } ``` - + 2. **Sensitive Data Redaction:** - Redact sensitive information before logging - Use dedicated functions for sanitization @@ -123,16 +123,16 @@ actions: function redactSensitiveData(obj) { const sensitiveFields = ['password', 'token', 'secret', 'creditCard', 'ssn']; const redacted = { ...obj }; - + for (const field of sensitiveFields) { if (field in redacted) { redacted[field] = '***REDACTED***'; } } - + return redacted; } - + // Usage logger.info({ message: 'User login attempt', @@ -140,7 +140,7 @@ actions: timestamp: new Date().toISOString() }); ``` - + 3. **Authentication Logging:** - Log all authentication events - Include success/failure status @@ -149,7 +149,7 @@ actions: async function authenticateUser(username, password) { try { const user = await User.findOne({ username }); - + if (!user) { logger.warn({ message: 'Authentication failed: user not found', @@ -160,9 +160,9 @@ actions: }); return { success: false, reason: 'invalid_credentials' }; } - + const isValid = await bcrypt.compare(password, user.passwordHash); - + if (!isValid) { logger.warn({ message: 'Authentication failed: invalid password', @@ -174,7 +174,7 @@ actions: }); return { success: false, reason: 'invalid_credentials' }; } - + logger.info({ message: 'User authenticated successfully', username, @@ -183,7 +183,7 @@ actions: userAgent: req.headers['user-agent'], timestamp: new Date().toISOString() }); - + return { success: true, user }; } catch (error) { logger.error({ @@ -200,17 +200,17 @@ actions: } } ``` - + 4. **Authorization Logging:** - Log access control decisions - Include user, resource, and action - Example: ```javascript function checkPermission(user, resource, action) { - const hasPermission = user.permissions.some(p => + const hasPermission = user.permissions.some(p => p.resource === resource && p.actions.includes(action) ); - + logger.info({ message: `Authorization ${hasPermission ? 'granted' : 'denied'}`, userId: user.id, @@ -220,11 +220,11 @@ actions: decision: hasPermission ? 'allow' : 'deny', timestamp: new Date().toISOString() }); - + return hasPermission; } ``` - + 5. **Comprehensive Error Logging:** - Include detailed error information - Add context for troubleshooting @@ -232,7 +232,7 @@ actions: ```javascript // Using a logging library like Winston const winston = require('winston'); - + const logger = winston.createLogger({ level: process.env.LOG_LEVEL || 'info', format: winston.format.combine( @@ -246,7 +246,7 @@ actions: new winston.transports.File({ filename: 'combined.log' }) ] }); - + // Usage try { // Operation that might fail @@ -269,7 +269,7 @@ actions: }); } ``` - + 6. **Security Event Logging:** - Log all security-relevant events - Include detailed context @@ -277,7 +277,7 @@ actions: ```javascript function detectBruteForce(username, ipAddress) { const attempts = getLoginAttempts(username, ipAddress); - + if (attempts > MAX_ATTEMPTS) { logger.warn({ message: 'Possible brute force attack detected', @@ -288,16 +288,16 @@ actions: action: 'account_temporarily_locked', timestamp: new Date().toISOString() }); - + // Implement account lockout or IP blocking lockAccount(username, LOCKOUT_DURATION); return true; } - + return false; } ``` - + 7. **Structured Logging Format:** - Use JSON for machine-readable logs - Maintain consistent field names @@ -305,7 +305,7 @@ actions: ```javascript // Using a structured logging library like Pino const pino = require('pino'); - + const logger = pino({ level: process.env.LOG_LEVEL || 'info', base: { pid: process.pid, hostname: os.hostname() }, @@ -316,7 +316,7 @@ actions: } } }); - + // Usage logger.info({ msg: 'User profile updated', @@ -325,7 +325,7 @@ actions: source: 'api' }); ``` - + 8. **Request Correlation:** - Use correlation IDs across services - Track request flow through the system @@ -333,21 +333,21 @@ actions: ```javascript // Express middleware for adding correlation IDs const { v4: uuidv4 } = require('uuid'); - + function correlationMiddleware(req, res, next) { // Use existing correlation ID from headers or generate a new one const correlationId = req.headers['x-correlation-id'] || uuidv4(); req.correlationId = correlationId; - + // Add to response headers res.setHeader('x-correlation-id', correlationId); - + // Add to logger context for this request req.logger = logger.child({ correlationId }); - + next(); } - + // Usage in route handlers app.get('/api/users/:id', (req, res) => { req.logger.info({ @@ -356,11 +356,11 @@ actions: path: req.path, method: req.method }); - + // Process request... }); ``` - + 9. **Transaction Logging:** - Log all high-value transactions - Include before/after states @@ -378,13 +378,13 @@ actions: transactionId: generateTransactionId(), timestamp: new Date().toISOString() }); - + try { const result = await paymentGateway.charge({ amount, source: paymentMethod.token }); - + logger.info({ message: 'Payment processed successfully', userId, @@ -394,7 +394,7 @@ actions: status: 'success', timestamp: new Date().toISOString() }); - + return { success: true, transactionId: result.transactionId }; } catch (error) { logger.error({ @@ -409,12 +409,12 @@ actions: status: 'failed', timestamp: new Date().toISOString() }); - + return { success: false, error: error.message }; } } ``` - + 10. **Client-Side Error Reporting:** - Send client errors to the backend - Include browser and user context @@ -436,7 +436,7 @@ actions: // Add user context if available userId: window.currentUser?.id }; - + // Send to backend logging endpoint fetch('/api/log/client-error', { method: 'POST', @@ -452,7 +452,7 @@ actions: }); }); ``` - + 11. **Proper Log Levels:** - Use appropriate log levels - Configure based on environment @@ -460,7 +460,7 @@ actions: ```javascript // Using Winston with proper log levels const winston = require('winston'); - + const logger = winston.createLogger({ level: process.env.NODE_ENV === 'production' ? 'info' : 'debug', levels: winston.config.npm.levels, @@ -477,7 +477,7 @@ actions: }) ] }); - + // Usage with appropriate levels logger.error('Critical application error'); // Always logged logger.warn('Potential issue detected'); // Warning conditions @@ -487,7 +487,7 @@ actions: logger.debug('Debugging information'); // For developers logger.silly('Extremely detailed tracing'); // Most granular ``` - + 12. **Monitoring Integration:** - Integrate with monitoring services - Set up alerts for critical issues @@ -497,9 +497,9 @@ actions: const Sentry = require('@sentry/node'); const Tracing = require('@sentry/tracing'); const express = require('express'); - + const app = express(); - + Sentry.init({ dsn: process.env.SENTRY_DSN, integrations: [ @@ -508,13 +508,13 @@ actions: ], tracesSampleRate: 1.0 }); - + // Use Sentry middleware app.use(Sentry.Handlers.requestHandler()); app.use(Sentry.Handlers.tracingHandler()); - + // Your routes here - + // Error handler app.use(Sentry.Handlers.errorHandler()); app.use((err, req, res, next) => { @@ -532,11 +532,11 @@ actions: correlationId: req.correlationId } }); - + res.status(500).json({ error: 'Internal server error' }); }); ``` - + 13. **Log Aggregation:** - Set up centralized log collection - Configure log shipping @@ -545,7 +545,7 @@ actions: // Using Winston with Elasticsearch transport const winston = require('winston'); const { ElasticsearchTransport } = require('winston-elasticsearch'); - + const esTransportOpts = { level: 'info', clientOpts: { @@ -557,7 +557,7 @@ actions: }, indexPrefix: 'app-logs' }; - + const logger = winston.createLogger({ transports: [ new winston.transports.Console(), @@ -565,7 +565,7 @@ actions: ] }); ``` - + ```yaml # docker-compose.yml example with ELK stack version: '3' @@ -577,7 +577,7 @@ actions: - ELASTICSEARCH_URL=http://elasticsearch:9200 depends_on: - elasticsearch - + elasticsearch: image: docker.elastic.co/elasticsearch/elasticsearch:7.14.0 environment: @@ -585,25 +585,25 @@ actions: - ES_JAVA_OPTS=-Xms512m -Xmx512m volumes: - es_data:/usr/share/elasticsearch/data - + kibana: image: docker.elastic.co/kibana/kibana:7.14.0 ports: - "5601:5601" depends_on: - elasticsearch - + logstash: image: docker.elastic.co/logstash/logstash:7.14.0 volumes: - ./logstash/pipeline:/usr/share/logstash/pipeline depends_on: - elasticsearch - + volumes: es_data: ``` - + 14. **Health Checks and Monitoring:** - Implement health check endpoints - Monitor application status @@ -611,7 +611,7 @@ actions: ```javascript const express = require('express'); const app = express(); - + // Basic health check endpoint app.get('/health', (req, res) => { const status = { @@ -621,7 +621,7 @@ actions: memoryUsage: process.memoryUsage(), version: process.env.npm_package_version }; - + // Add database health check try { // Check database connection @@ -630,60 +630,60 @@ actions: status.database = { status: 'DOWN', error: error.message }; status.status = 'DEGRADED'; } - + // Add external service health checks // ... - + // Log health check results logger.debug({ message: 'Health check performed', result: status }); - - const statusCode = status.status === 'UP' ? 200 : + + const statusCode = status.status === 'UP' ? 200 : status.status === 'DEGRADED' ? 200 : 503; - + res.status(statusCode).json(status); }); - + // Detailed readiness probe app.get('/ready', async (req, res) => { const checks = []; let isReady = true; - + // Check database try { await db.ping(); checks.push({ component: 'database', status: 'ready' }); } catch (error) { isReady = false; - checks.push({ - component: 'database', + checks.push({ + component: 'database', status: 'not ready', error: error.message }); } - + // Check cache try { await cache.ping(); checks.push({ component: 'cache', status: 'ready' }); } catch (error) { isReady = false; - checks.push({ - component: 'cache', + checks.push({ + component: 'cache', status: 'not ready', error: error.message }); } - + // Log readiness check logger.debug({ message: 'Readiness check performed', isReady, checks }); - + res.status(isReady ? 200 : 503).json({ status: isReady ? 'ready' : 'not ready', checks, @@ -691,14 +691,14 @@ actions: }); }); ``` - + 15. **Rate Limiting with Logging:** - Log rate limit events - Track potential abuse - Example: ```javascript const rateLimit = require('express-rate-limit'); - + // Create rate limiter with logging const apiLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes @@ -719,7 +719,7 @@ actions: userId: req.user?.id, timestamp: new Date().toISOString() }); - + res.status(options.statusCode).json({ status: 'error', message: options.message @@ -738,12 +738,12 @@ actions: userId: req.user?.id, timestamp: new Date().toISOString() }); - + // Consider additional actions like temporary IP ban // or sending alerts for potential attacks } }); - + // Apply to all API routes app.use('/api/', apiLimiter); ``` @@ -753,19 +753,19 @@ actions: # Check 1: Structured Logging - pattern: "(?:winston|pino|bunyan|loglevel|morgan|log4js)" message: "Using a structured logging library." - + # Check 2: Error Logging - pattern: "try\\s*{[^}]*}\\s*catch\\s*\\([^)]*\\)\\s*{[^}]*(?:logger?\\.error|captureException)\\s*\\([^)]*\\)" message: "Implementing proper error logging in catch blocks." - + # Check 3: Sensitive Data Handling - pattern: "(?:redact|mask|sanitize|filter)\\s*\\([^)]*(?:password|token|secret|key|credential)" message: "Implementing sensitive data redaction in logs." - + # Check 4: Correlation IDs - pattern: "(?:correlationId|requestId|traceId)" message: "Using correlation IDs for request tracing." - + # Check 5: Monitoring Integration - pattern: "(?:sentry|newrelic|datadog|appinsights|loggly|splunk|elasticsearch)" message: "Integrating with monitoring or log aggregation services." @@ -798,4 +798,6 @@ metadata: - "https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html#security-logging-monitoring" - "https://cheatsheetseries.owasp.org/cheatsheets/Application_Logging_Vocabulary_Cheat_Sheet.html" - "https://cheatsheetseries.owasp.org/cheatsheets/Transaction_Authorization_Cheat_Sheet.html#monitor-activity" - +``` + + diff --git a/.cursor/rules/javascript-security-misconfiguration.mdc b/.cursor/rules/javascript-security-misconfiguration.mdc index b6acbbb..f4fbc7a 100644 --- a/.cursor/rules/javascript-security-misconfiguration.mdc +++ b/.cursor/rules/javascript-security-misconfiguration.mdc @@ -4,7 +4,7 @@ globs: **/*.js, **/*.jsx, **/*.ts, **/*.tsx, !**/node_modules/**, !**/dist/**, ! --- # JavaScript Security Misconfiguration (OWASP A05:2021) - +```yaml name: javascript_security_misconfiguration description: Detect and prevent security misconfigurations in JavaScript applications as defined in OWASP Top 10:2021-A05 @@ -15,67 +15,67 @@ actions: - pattern: "app\\.use\\([^)]*?\\)\\s*(?!.*(?:helmet|frameguard|hsts|noSniff|xssFilter|contentSecurityPolicy))" location: "(?:app|server|index)\\.(?:js|ts)$" message: "Missing HTTP security headers. Consider using Helmet.js to set secure HTTP headers." - + # Pattern 2: Insecure CORS Configuration - pattern: "app\\.use\\(cors\\(\\{[^}]*?origin\\s*:\\s*['\"]\\*['\"]\\s*\\}\\)\\)" message: "Insecure CORS configuration. Avoid using wildcard (*) for CORS origin in production environments." - + # Pattern 3: Exposed Environment Variables in Client-Side Code - pattern: "process\\.env\\.[A-Z_]+" location: "(?:src|components|pages)" message: "Exposing environment variables in client-side code. Only use environment variables with NEXT_PUBLIC_, REACT_APP_, or VITE_ prefixes for client-side code." - + # Pattern 4: Insecure Cookie Settings - pattern: "(?:cookie|cookies|session)\\([^)]*?\\{[^}]*?(?:secure\\s*:\\s*false|httpOnly\\s*:\\s*false|sameSite\\s*:\\s*['\"]none['\"])" message: "Insecure cookie configuration. Set secure:true, httpOnly:true, and appropriate sameSite value for cookies." - + # Pattern 5: Missing Content Security Policy - pattern: "app\\.use\\([^)]*?helmet\\([^)]*?\\{[^}]*?contentSecurityPolicy\\s*:\\s*false" message: "Content Security Policy (CSP) is disabled. Enable and configure CSP to prevent XSS attacks." - + # Pattern 6: Debug Information Exposure - pattern: "app\\.use\\([^)]*?morgan\\(['\"]dev['\"]\\)|console\\.(?:log|debug|info|warn|error)\\(" location: "(?:app|server|index)\\.(?:js|ts)$" message: "Debug information might be exposed in production. Ensure logging is properly configured based on the environment." - + # Pattern 7: Insecure Server Configuration - pattern: "app\\.disable\\(['\"]x-powered-by['\"]\\)" negative_pattern: true location: "(?:app|server|index)\\.(?:js|ts)$" message: "X-Powered-By header is not disabled. Use app.disable('x-powered-by') to hide technology information." - + # Pattern 8: Directory Listing Enabled - pattern: "express\\.static\\([^)]*?\\{[^}]*?index\\s*:\\s*false" message: "Directory listing might be enabled. Set index:true or provide an index file to prevent directory listing." - + # Pattern 9: Missing Rate Limiting - pattern: "app\\.(?:get|post|put|delete|patch)\\([^)]*?['\"](?:/api|/login|/register|/auth)['\"]" negative_pattern: "(?:rateLimit|rateLimiter|limiter|throttle)" message: "Missing rate limiting for sensitive endpoints. Implement rate limiting to prevent brute force attacks." - + # Pattern 10: Insecure WebSocket Configuration - pattern: "new\\s+WebSocket\\([^)]*?\\)|io\\.on\\(['\"]connection['\"]" negative_pattern: "(?:wss://|https://)" message: "Potentially insecure WebSocket connection. Use secure WebSocket (wss://) in production." - + # Pattern 11: Hardcoded Configuration Values - pattern: "(?:apiKey|secret|password|token|credentials)\\s*=\\s*['\"][^'\"]+['\"]" message: "Hardcoded configuration values. Use environment variables or a secure configuration management system." - + # Pattern 12: Insecure SSL/TLS Configuration - pattern: "https\\.createServer\\([^)]*?\\{[^}]*?rejectUnauthorized\\s*:\\s*false" message: "Insecure SSL/TLS configuration. Never set rejectUnauthorized:false in production." - + # Pattern 13: Missing Security Middleware - pattern: "express\\(\\)|require\\(['\"]express['\"]\\)" negative_pattern: "(?:helmet|cors|rateLimit|bodyParser\\.json\\(\\{\\s*limit|express\\.json\\(\\{\\s*limit)" location: "(?:app|server|index)\\.(?:js|ts)$" message: "Missing essential security middleware. Consider using helmet, cors, rate limiting, and request size limiting." - + # Pattern 14: Insecure Error Handling - pattern: "app\\.use\\([^)]*?function\\s*\\([^)]*?err[^)]*?\\)\\s*\\{[^}]*?res\\.status[^}]*?err(?:\\.message|\\.stack)" message: "Insecure error handling. Avoid exposing error details like stack traces to clients in production." - + # Pattern 15: Outdated Dependencies Warning - pattern: "(?:\"dependencies\"|\"devDependencies\")\\s*:\\s*\\{[^}]*?['\"](?:express|react|vue|angular|next|nuxt|axios)['\"]\\s*:\\s*['\"]\\^?\\d+\\.\\d+\\.\\d+['\"]" location: "package\\.json$" @@ -84,17 +84,17 @@ actions: - type: suggest message: | **JavaScript Security Configuration Best Practices:** - + 1. **HTTP Security Headers:** - Use Helmet.js to set secure HTTP headers - Configure Content Security Policy (CSP) - Example: ```javascript const helmet = require('helmet'); - + // Basic usage app.use(helmet()); - + // Custom CSP configuration app.use( helmet.contentSecurityPolicy({ @@ -113,32 +113,32 @@ actions: }) ); ``` - + 2. **Secure CORS Configuration:** - Specify allowed origins explicitly - Configure appropriate CORS options - Example: ```javascript const cors = require('cors'); - + // Define allowed origins const allowedOrigins = [ 'https://yourdomain.com', 'https://app.yourdomain.com', 'https://admin.yourdomain.com' ]; - + // Configure CORS app.use(cors({ origin: function(origin, callback) { // Allow requests with no origin (like mobile apps, curl, etc.) if (!origin) return callback(null, true); - + if (allowedOrigins.indexOf(origin) === -1) { const msg = 'The CORS policy for this site does not allow access from the specified Origin.'; return callback(new Error(msg), false); } - + return callback(null, true); }, methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], @@ -146,7 +146,7 @@ actions: maxAge: 86400 // 24 hours })); ``` - + 3. **Environment-Based Configuration:** - Use different configurations for development and production - Validate configuration at startup @@ -155,23 +155,23 @@ actions: const express = require('express'); const helmet = require('helmet'); const morgan = require('morgan'); - + const app = express(); - + // Environment-specific configuration if (process.env.NODE_ENV === 'production') { // Production settings app.use(helmet()); app.use(morgan('combined')); app.set('trust proxy', 1); // Trust first proxy - + // Disable X-Powered-By header app.disable('x-powered-by'); } else { // Development settings app.use(morgan('dev')); } - + // Validate required environment variables const requiredEnvVars = ['DATABASE_URL', 'JWT_SECRET']; for (const envVar of requiredEnvVars) { @@ -181,14 +181,14 @@ actions: } } ``` - + 4. **Secure Cookie Configuration:** - Set secure, httpOnly, and sameSite attributes - Use signed cookies when appropriate - Example: ```javascript const session = require('express-session'); - + app.use(session({ secret: process.env.SESSION_SECRET, name: 'sessionId', // Custom cookie name instead of default @@ -203,7 +203,7 @@ actions: saveUninitialized: false })); ``` - + 5. **Request Size Limiting:** - Limit request body size to prevent DoS attacks - Example: @@ -211,13 +211,13 @@ actions: // Using express built-in middleware app.use(express.json({ limit: '10kb' })); app.use(express.urlencoded({ extended: true, limit: '10kb' })); - + // Or using body-parser const bodyParser = require('body-parser'); app.use(bodyParser.json({ limit: '10kb' })); app.use(bodyParser.urlencoded({ extended: true, limit: '10kb' })); ``` - + 6. **Proper Error Handling:** - Use a centralized error handler - Don't expose sensitive information in error responses @@ -230,16 +230,16 @@ actions: this.statusCode = statusCode; this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error'; this.isOperational = true; - + Error.captureStackTrace(this, this.constructor); } } - + // Global error handling middleware app.use((err, req, res, next) => { err.statusCode = err.statusCode || 500; err.status = err.status || 'error'; - + // Different handling for development and production if (process.env.NODE_ENV === 'development') { res.status(err.statusCode).json({ @@ -258,7 +258,7 @@ actions: } else { // Log programming or unknown errors console.error('ERROR 💥', err); - + // Send generic message res.status(500).json({ status: 'error', @@ -268,14 +268,14 @@ actions: } }); ``` - + 7. **Rate Limiting:** - Apply rate limiting to sensitive endpoints - Use different limits for different endpoints - Example: ```javascript const rateLimit = require('express-rate-limit'); - + // Create a rate limiter for API endpoints const apiLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes @@ -284,7 +284,7 @@ actions: legacyHeaders: false, // Disable the `X-RateLimit-*` headers message: 'Too many requests from this IP, please try again after 15 minutes' }); - + // Create a stricter rate limiter for authentication endpoints const authLimiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes @@ -293,12 +293,12 @@ actions: legacyHeaders: false, message: 'Too many login attempts from this IP, please try again after 15 minutes' }); - + // Apply rate limiters to routes app.use('/api/', apiLimiter); app.use('/api/auth/', authLimiter); ``` - + 8. **Secure WebSocket Configuration:** - Use secure WebSocket connections (wss://) - Implement authentication for WebSocket connections @@ -308,9 +308,9 @@ actions: const https = require('https'); const socketIo = require('socket.io'); const fs = require('fs'); - + let server; - + // Create secure server in production if (process.env.NODE_ENV === 'production') { const options = { @@ -321,32 +321,32 @@ actions: } else { server = http.createServer(app); } - + const io = socketIo(server, { cors: { - origin: process.env.NODE_ENV === 'production' - ? 'https://yourdomain.com' + origin: process.env.NODE_ENV === 'production' + ? 'https://yourdomain.com' : 'http://localhost:3000', methods: ['GET', 'POST'], credentials: true } }); - + // WebSocket authentication middleware io.use((socket, next) => { const token = socket.handshake.auth.token; - + if (!token) { return next(new Error('Authentication error')); } - + // Verify token // ... - + next(); }); ``` - + 9. **Security Dependency Management:** - Regularly update dependencies - Use tools like npm audit or Snyk @@ -363,14 +363,14 @@ actions: } } ``` - + 10. **Secure Logging Configuration:** - Configure logging based on environment - Avoid logging sensitive information - Example: ```javascript const winston = require('winston'); - + // Define log levels const levels = { error: 0, @@ -379,13 +379,13 @@ actions: http: 3, debug: 4, }; - + // Define log level based on environment const level = () => { const env = process.env.NODE_ENV || 'development'; return env === 'development' ? 'debug' : 'warn'; }; - + // Define log format const format = winston.format.combine( winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss:ms' }), @@ -393,7 +393,7 @@ actions: (info) => `${info.timestamp} ${info.level}: ${info.message}` ) ); - + // Define transports const transports = [ new winston.transports.Console(), @@ -403,7 +403,7 @@ actions: }), new winston.transports.File({ filename: 'logs/all.log' }), ]; - + // Create the logger const logger = winston.createLogger({ level: level(), @@ -411,7 +411,7 @@ actions: format, transports, }); - + module.exports = logger; ``` @@ -420,19 +420,19 @@ actions: # Check 1: Helmet usage - pattern: "helmet\\(\\)|frameguard\\(\\)|hsts\\(\\)|noSniff\\(\\)|xssFilter\\(\\)|contentSecurityPolicy\\(\\)" message: "Using Helmet.js or individual HTTP security headers middleware." - + # Check 2: Secure CORS configuration - pattern: "cors\\(\\{[^}]*?origin\\s*:\\s*(?!['\"]*\\*)['\"]" message: "Using secure CORS configuration with specific origins." - + # Check 3: Environment-based configuration - pattern: "process\\.env\\.NODE_ENV\\s*===\\s*['\"]production['\"]" message: "Implementing environment-specific configuration." - + # Check 4: Secure cookie settings - pattern: "cookie\\s*:\\s*\\{[^}]*?secure\\s*:\\s*true[^}]*?httpOnly\\s*:\\s*true" message: "Using secure cookie configuration." - + # Check 5: Request size limiting - pattern: "(?:express|bodyParser)\\.json\\(\\{[^}]*?limit\\s*:" message: "Implementing request size limiting." @@ -464,4 +464,6 @@ metadata: - "https://github.com/OWASP/NodeGoat" - "https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html" - "https://cheatsheetseries.owasp.org/cheatsheets/Content_Security_Policy_Cheat_Sheet.html" - +``` + + diff --git a/.cursor/rules/javascript-server-side-request-forgery.mdc b/.cursor/rules/javascript-server-side-request-forgery.mdc index d50c835..88250fc 100644 --- a/.cursor/rules/javascript-server-side-request-forgery.mdc +++ b/.cursor/rules/javascript-server-side-request-forgery.mdc @@ -4,7 +4,7 @@ globs: **/*.js, **/*.jsx, **/*.ts, **/*.tsx, !**/node_modules/**, !**/dist/**, ! --- # JavaScript Server-Side Request Forgery (OWASP A10:2021) - +```yaml name: javascript_server_side_request_forgery description: Detect and prevent Server-Side Request Forgery (SSRF) vulnerabilities in JavaScript applications as defined in OWASP Top 10:2021-A10 @@ -14,65 +14,65 @@ actions: # Pattern 1: URL from User Input - pattern: "(fetch|axios\\.get|axios\\.post|axios\\.put|axios\\.delete|axios\\.patch|http\\.get|http\\.request|https\\.get|https\\.request|\\$\\.ajax|XMLHttpRequest|got|request|superagent|needle)\\s*\\([^)]*(?:\\$_GET|\\$_POST|\\$_REQUEST|req\\.(?:body|query|params)|request\\.(?:body|query|params)|event\\.(?:body|queryStringParameters|pathParameters)|params|userInput|data\\[" message: "Potential SSRF vulnerability: URL constructed from user input. Implement URL validation, allowlisting, or use a URL parser library to validate and sanitize user-provided URLs." - + # Pattern 2: Dynamic URL in HTTP Request - pattern: "(fetch|axios|http\\.get|http\\.request|https\\.get|https\\.request|\\$\\.ajax|XMLHttpRequest|got|request|superagent|needle)\\s*\\(\\s*['\"`]https?:\\/\\/[^'\"`]*['\"`]\\s*\\+\\s*" message: "Potential SSRF vulnerability: Dynamic URL in HTTP request. Use URL parsing and validation before making the request." - + # Pattern 3: URL Redirection Without Validation - pattern: "(res\\.redirect|res\\.location|window\\.location|location\\.href|location\\.replace|location\\.assign|location\\.port|history\\.pushState|history\\.replaceState)\\s*\\([^)]*(?:req\\.(?:query|body|params)|request\\.(?:query|body|params)|userInput)" message: "URL redirection without proper validation may lead to SSRF. Implement strict validation for URLs before redirecting." - + # Pattern 4: Direct IP Address Usage - pattern: "(fetch|axios\\.get|axios\\.post|axios\\.put|axios\\.delete|axios\\.patch|http\\.get|http\\.request|https\\.get|https\\.request)\\s*\\(\\s*['\"`]https?:\\/\\/\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}" message: "Direct use of IP addresses in requests may bypass hostname-based restrictions. Consider using allowlisted hostnames instead." - + # Pattern 5: Local Network Access - pattern: "(fetch|axios\\.get|axios\\.post|axios\\.put|axios\\.delete|axios\\.patch|http\\.get|http\\.request|https\\.get|https\\.request)\\s*\\(\\s*['\"`]https?:\\/\\/(?:localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|192\\.168\\.|10\\.|172\\.(?:1[6-9]|2[0-9]|3[0-1])\\.|::1)" message: "Request to internal network address detected. Restrict access to internal resources to prevent SSRF attacks." - + # Pattern 6: File Protocol Usage - pattern: "(fetch|axios\\.get|axios\\.post|axios\\.put|axios\\.delete|axios\\.patch|http\\.get|http\\.request|https\\.get|https\\.request)\\s*\\(\\s*['\"`]file:\\/\\/" message: "Use of file:// protocol may lead to local file access. Block or restrict file:// protocol usage." - + # Pattern 7: Missing URL Validation - pattern: "(fetch|axios\\.get|axios\\.post|axios\\.put|axios\\.delete|axios\\.patch|http\\.get|http\\.request|https\\.get|https\\.request)\\s*\\([^)]*\\burl\\b[^)]*\\)" negative_pattern: "(validat|sanitiz|check|parse).*\\burl\\b|allowlist|whitelist|URL\\.(parse|canParse)|new URL\\(|isValidURL" message: "HTTP request without URL validation. Implement URL validation before making external requests." - + # Pattern 8: HTTP Request in User-Defined Function - pattern: "function\\s+[a-zA-Z0-9_]*(?:request|fetch|get|http|curl)\\s*\\([^)]*\\)\\s*\\{[^}]*(?:fetch|axios|http\\.get|http\\.request|https\\.get|https\\.request)" negative_pattern: "(validat|sanitiz|check|parse).*\\burl\\b|allowlist|whitelist|new URL\\(|isValidURL" message: "User-defined HTTP request function without URL validation. Implement proper URL validation and sanitization." - + # Pattern 9: Proxy Functionality - pattern: "(?:proxy|forward|relay).*(?:req\\.(?:url|path)|request\\.(?:url|path))" negative_pattern: "(validat|sanitiz|check|parse).*\\burl\\b|allowlist|whitelist" message: "Proxy or request forwarding functionality detected. Implement strict URL validation and allowlisting." - + # Pattern 10: Alternative HTTP Methods - pattern: "(fetch|axios)\\s*\\([^)]*method\\s*:\\s*['\"`](?:GET|POST|PUT|DELETE|PATCH|OPTIONS|HEAD)['\"`]" negative_pattern: "(validat|sanitiz|check|parse).*\\burl\\b|allowlist|whitelist|new URL\\(|isValidURL" message: "HTTP request with explicit method without URL validation. Implement URL validation for all HTTP methods." - + # Pattern 11: URL Building from Parts - pattern: "new URL\\s*\\((?:[^,)]+,\\s*){1,}(?:req\\.(?:body|query|params)|request\\.(?:body|query|params)|userinput)" message: "Building URL with user input. Validate and sanitize all URL components and use an allowlist for base URLs." - + # Pattern 12: Protocol-Relative URLs - pattern: "(fetch|axios)\\s*\\(['\"`]\\/\\/[^'\"`]+['\"`]" message: "Protocol-relative URL usage may lead to SSRF. Always specify the protocol and validate URLs." - + # Pattern 13: Express-like Route with URL Parameter - pattern: "app\\.(?:get|post|put|delete|patch)\\s*\\(['\"`][^'\"`]*\\/:[a-zA-Z0-9_]+(?:\\/|['\"`])" negative_pattern: "(validat|sanitiz|check|parse).*\\burl\\b|allowlist|whitelist|new URL\\(|isValidURL" message: "Route with dynamic parameter that might be used in URL construction. Ensure proper validation before making any HTTP requests within this route handler." - + # Pattern 14: URL Parsing without Validation - pattern: "URL\\.parse\\s*\\(|new URL\\s*\\(" negative_pattern: "try\\s*\\{|catch\\s*\\(|validat|sanitiz|check" message: "URL parsing without validation or error handling. Implement proper error handling and validation for URL parsing." - + # Pattern 15: Service Discovery / Cloud Metadata Access - pattern: "(fetch|axios\\.get|http\\.get)\\s*\\(['\"`]https?:\\/\\/(?:169\\.254\\.169\\.254|fd00:ec2|metadata\\.google|metadata\\.azure|169\\.254\\.169\\.254\\/latest\\/meta-data)" message: "Access to cloud service metadata endpoints detected. Restrict access to cloud metadata services to prevent server information disclosure." @@ -80,7 +80,7 @@ actions: - type: suggest message: | **JavaScript Server-Side Request Forgery (SSRF) Prevention Best Practices:** - + 1. **Implement URL Validation and Sanitization:** - Use built-in URL parsing libraries to validate URLs - Validate both the URL format and components @@ -100,16 +100,16 @@ actions: return false; } } - + // Usage const userProvidedUrl = req.body.targetUrl; if (!isValidUrl(userProvidedUrl)) { return res.status(400).json({ error: 'Invalid URL format or protocol' }); } - + // Now make the request with the validated URL ``` - + 2. **Implement Strict Allowlisting:** - Define allowlist of permitted domains and endpoints - Reject requests to any domains not on the allowlist @@ -120,7 +120,7 @@ actions: 'cdn.example.com', 'partner-api.trusted-domain.com' ]; - + function isAllowedDomain(url) { try { const parsedUrl = new URL(url); @@ -129,7 +129,7 @@ actions: return false; } } - + // Usage const targetUrl = req.body.webhookUrl; if (!isAllowedDomain(targetUrl)) { @@ -142,7 +142,7 @@ actions: return res.status(403).json({ error: 'Domain not allowed' }); } ``` - + 3. **Block Access to Internal Networks:** - Prevent requests to private IP ranges - Block localhost and internal hostnames @@ -155,7 +155,7 @@ actions: } return false; } - + function isPrivateIP(ip) { // Check for private IP ranges const privateRanges = [ @@ -168,19 +168,19 @@ actions: /^f[cd][0-9a-f]{2}:/i, // fc00::/7 unique local IPv6 /^fe80:/i // fe80::/10 link-local IPv6 ]; - + return privateRanges.some(range => range.test(ip)); } - + function isUrlSafe(url) { try { const parsedUrl = new URL(url); - + // Block internal hostnames if (isInternalHostname(parsedUrl.hostname)) { return false; } - + // Resolve hostname to IP (in real implementation, use async DNS resolution) // This example is simplified - in production you would use DNS resolution let ip; @@ -188,7 +188,7 @@ actions: // Note: This is a pseudo-code example // In real code, you'd use a DNS resolution library ip = dnsResolve(parsedUrl.hostname); - + // Block private IPs if (isPrivateIP(ip)) { return false; @@ -197,14 +197,14 @@ actions: // If DNS resolution fails, err on the side of caution return false; } - + return true; } catch (error) { return false; } } ``` - + 4. **Disable Dangerous URL Protocols:** - Restrict allowed URL protocols to HTTP and HTTPS - Block file://, ftp://, gopher://, etc. @@ -219,7 +219,7 @@ actions: return false; } } - + // Usage const targetUrl = req.body.documentUrl; if (!hasAllowedProtocol(targetUrl)) { @@ -232,7 +232,7 @@ actions: return res.status(403).json({ error: 'URL protocol not allowed' }); } ``` - + 5. **Implement Network-Level Protection:** - Use firewall rules to block outbound requests to internal networks - Configure proxy servers to restrict external requests @@ -241,14 +241,14 @@ actions: // Using a proxy for outbound requests const axios = require('axios'); const HttpsProxyAgent = require('https-proxy-agent'); - + // Configure proxy with appropriate controls const httpsAgent = new HttpsProxyAgent({ host: 'proxy.example.com', port: 3128, // This proxy should be configured to block access to internal networks }); - + // Make requests through the proxy async function secureExternalRequest(url) { try { @@ -268,7 +268,7 @@ actions: } } ``` - + 6. **Use Service-Specific Endpoints:** - Instead of passing full URLs, use service identifiers - Map identifiers to URLs on the server side @@ -277,19 +277,19 @@ actions: // Client makes request with service identifier, not raw URL app.get('/proxy-service/:serviceId', async (req, res) => { const { serviceId } = req.params; - + // Service mapping defined server-side const serviceMap = { 'weather-api': 'https://api.weather.example.com/current', 'news-feed': 'https://api.news.example.com/feed', 'product-info': 'https://api.products.example.com/details' }; - + // Check if service is defined if (!serviceMap[serviceId]) { return res.status(404).json({ error: 'Service not found' }); } - + try { // Make request to mapped URL (not user-controlled) const response = await axios.get(serviceMap[serviceId]); @@ -299,7 +299,7 @@ actions: } }); ``` - + 7. **Implement Context-Specific Encodings:** - Use context-appropriate encoding for URL parameters - Don't rely solely on standard URL encoding @@ -308,21 +308,21 @@ actions: function safeUrl(baseUrl, params) { // Start with a verified base URL const url = new URL(baseUrl); - + // Add parameters safely for (const [key, value] of Object.entries(params)) { // Ensure values are strings and properly encoded url.searchParams.append(key, String(value)); } - + // Verify the final URL is still valid if (!isAllowedDomain(url.toString())) { throw new Error('URL creation resulted in disallowed domain'); } - + return url.toString(); } - + // Usage try { const apiUrl = safeUrl('https://api.example.com/data', { @@ -335,7 +335,7 @@ actions: // Handle error } ``` - + 8. **Use Defense in Depth:** - Combine multiple validation strategies - Don't rely on a single protection measure @@ -346,23 +346,23 @@ actions: if (!isValidUrl(url)) { throw new Error('Invalid URL format'); } - + // 2. Check against allowlist if (!isAllowedDomain(url)) { throw new Error('Domain not in allowlist'); } - + // 3. Verify not internal network const parsedUrl = new URL(url); if (await isInternalNetwork(parsedUrl.hostname)) { throw new Error('Access to internal networks not allowed'); } - + // 4. Validate protocol if (!hasAllowedProtocol(url)) { throw new Error('Protocol not allowed'); } - + // 5. Set additional security headers and options const secureOptions = { ...options, @@ -373,7 +373,7 @@ actions: 'User-Agent': 'SecureApp/1.0' } }; - + // 6. Make request with all validations passed try { return await axios(url, secureOptions); @@ -387,7 +387,7 @@ actions: } } ``` - + 9. **Validate and Sanitize Request Parameters:** - Don't trust any user-supplied input for URL construction - Validate all components used in URL building @@ -396,23 +396,23 @@ actions: // API that fetches weather data for a city app.get('/api/weather', async (req, res) => { const { city } = req.query; - + // 1. Validate parameter exists and is valid if (!city || typeof city !== 'string' || city.length > 100) { return res.status(400).json({ error: 'Invalid city parameter' }); } - + // 2. Sanitize the parameter const sanitizedCity = encodeURIComponent(city.trim()); - + // 3. Construct URL with validated parameter const weatherApiUrl = `https://api.weather.example.com/current?city=${sanitizedCity}`; - + // 4. Additional validation of the final URL if (!isValidUrl(weatherApiUrl)) { return res.status(400).json({ error: 'Invalid URL construction' }); } - + try { const response = await axios.get(weatherApiUrl); return res.json(response.data); @@ -426,7 +426,7 @@ actions: } }); ``` - + 10. **Implement Request Timeouts:** - Set appropriate timeouts for all HTTP requests - Prevent long-running SSRF probes @@ -435,17 +435,17 @@ actions: async function fetchWithTimeout(url, options = {}) { // Default timeout of 5 seconds const timeout = options.timeout || 5000; - + // Create an abort controller to handle timeout const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), timeout); - + try { const response = await fetch(url, { ...options, signal: controller.signal }); - + clearTimeout(timeoutId); return response; } catch (error) { @@ -456,7 +456,7 @@ actions: throw error; } } - + // Usage try { const response = await fetchWithTimeout('https://api.example.com/data', { @@ -469,40 +469,40 @@ actions: console.error('Request failed:', error.message); } ``` - + 11. **Rate Limit External Requests:** - Implement rate limiting for outbound requests - Prevent SSRF probing and DoS attacks - Example: ```javascript const { RateLimiter } = require('limiter'); - + // Create a rate limiter: 100 requests per minute const externalRequestLimiter = new RateLimiter({ tokensPerInterval: 100, interval: 'minute' }); - + async function rateLimitedRequest(url, options = {}) { // Check if we have tokens available const remainingRequests = await externalRequestLimiter.removeTokens(1); - + if (remainingRequests < 0) { throw new Error('Rate limit exceeded for external requests'); } - + // Proceed with the request return axios(url, options); } - + // Usage app.get('/api/external-data', async (req, res) => { const { url } = req.query; - + if (!isValidUrl(url) || !isAllowedDomain(url)) { return res.status(403).json({ error: 'URL not allowed' }); } - + try { const response = await rateLimitedRequest(url); return res.json(response.data); @@ -514,7 +514,7 @@ actions: } }); ``` - + 12. **Use Web Application Firewalls (WAF):** - Configure WAF rules to detect and block SSRF patterns - Implement server-side firewall rules @@ -523,11 +523,11 @@ actions: // Middleware to detect SSRF attack patterns function ssrfProtectionMiddleware(req, res, next) { const url = req.query.url || req.body.url; - + if (!url) { return next(); } - + // Check for suspicious URL patterns const ssrfPatterns = [ /file:\/\//i, @@ -536,7 +536,7 @@ actions: /(localhost|127\.0\.0\.1|0\.0\.0\.0|::1)/i, /^(10\.|172\.(1[6-9]|2[0-9]|3[0-1])\.|192\.168\.)/ ]; - + if (ssrfPatterns.some(pattern => pattern.test(url))) { logger.warn({ message: 'Potential SSRF attack detected', @@ -546,19 +546,19 @@ actions: method: req.method, userId: req.user?.id }); - + return res.status(403).json({ error: 'Access denied - suspicious URL detected' }); } - + next(); } - + // Apply middleware to all routes app.use(ssrfProtectionMiddleware); ``` - + 13. **Implement Centralized Request Services:** - Create a dedicated service for external requests - Implement all security controls in one place @@ -566,7 +566,7 @@ actions: ```javascript // externalRequestService.js const axios = require('axios'); - + class ExternalRequestService { constructor(options = {}) { this.allowedDomains = options.allowedDomains || []; @@ -574,18 +574,18 @@ actions: this.timeout = options.timeout || 5000; this.logger = options.logger || console; } - + async request(url, options = {}) { // Validate URL if (!this._isValidUrl(url)) { throw new Error('Invalid URL format'); } - + // Check allowlist if (!this._isAllowedDomain(url)) { throw new Error('Domain not in allowlist'); } - + // Configure request options const requestOptions = { ...options, @@ -593,7 +593,7 @@ actions: maxRedirects: options.maxRedirects || this.maxRedirects, validateStatus: status => status >= 200 && status < 300 }; - + try { const response = await axios(url, requestOptions); return response.data; @@ -606,7 +606,7 @@ actions: throw new Error(`External request failed: ${error.message}`); } } - + _isValidUrl(url) { try { const parsedUrl = new URL(url); @@ -615,7 +615,7 @@ actions: return false; } } - + _isAllowedDomain(url) { try { const parsedUrl = new URL(url); @@ -625,12 +625,12 @@ actions: } } } - + module.exports = ExternalRequestService; - + // Usage in application const ExternalRequestService = require('./externalRequestService'); - + const requestService = new ExternalRequestService({ allowedDomains: [ 'api.example.com', @@ -640,7 +640,7 @@ actions: logger: appLogger, timeout: 3000 }); - + app.get('/api/external-data', async (req, res) => { try { // Use the service for all external requests @@ -651,7 +651,7 @@ actions: } }); ``` - + 14. **Monitor and Audit External Requests:** - Log all external requests for audit purposes - Implement anomaly detection @@ -663,17 +663,17 @@ actions: if (!req.path.startsWith('/api/proxy') && !req.path.startsWith('/api/external')) { return next(); } - + // Store original fetch/http.request methods const originalFetch = global.fetch; const originalHttpRequest = require('http').request; const originalHttpsRequest = require('https').request; - + // Override fetch global.fetch = async function monitoredFetch(url, options) { const requestId = uuid.v4(); const startTime = Date.now(); - + logger.info({ message: 'External request initiated', requestId, @@ -686,10 +686,10 @@ actions: }, timestamp: new Date().toISOString() }); - + try { const response = await originalFetch(url, options); - + // Log successful request logger.info({ message: 'External request completed', @@ -699,7 +699,7 @@ actions: duration: Date.now() - startTime, timestamp: new Date().toISOString() }); - + return response; } catch (error) { // Log failed request @@ -711,14 +711,14 @@ actions: duration: Date.now() - startTime, timestamp: new Date().toISOString() }); - + throw error; } }; - + // Similar overrides for http.request and https.request // ... - + // Continue with the request res.on('finish', () => { // Restore original methods after request completes @@ -726,21 +726,21 @@ actions: require('http').request = originalHttpRequest; require('https').request = originalHttpsRequest; }); - + next(); } - + // Apply middleware app.use(requestMonitoringMiddleware); ``` - + 15. **Implement Output Validation:** - Validate responses from external services - Use schema validation for expected formats - Example: ```javascript const Joi = require('joi'); - + // Define expected schemas for external APIs const apiSchemas = { weatherApi: Joi.object({ @@ -749,21 +749,21 @@ actions: conditions: Joi.string().required(), forecast: Joi.array().items(Joi.object()) }), - + userApi: Joi.object({ id: Joi.string().required(), name: Joi.string().required(), email: Joi.string().email().required() }) }; - + async function validateExternalResponse(data, schemaName) { const schema = apiSchemas[schemaName]; - + if (!schema) { throw new Error(`Schema not found: ${schemaName}`); } - + try { const result = await schema.validateAsync(data); return result; @@ -774,23 +774,23 @@ actions: error: error.message, data: JSON.stringify(data).substring(0, 200) // Log partial data for debugging }); - + throw new Error(`Invalid response format from external API: ${error.message}`); } } - + // Usage app.get('/api/weather/:city', async (req, res) => { const { city } = req.params; - + try { // Fetch data from external API const apiUrl = `https://api.weather.example.com/current?city=${encodeURIComponent(city)}`; const response = await axios.get(apiUrl); - + // Validate the response against the expected schema const validatedData = await validateExternalResponse(response.data, 'weatherApi'); - + // Return the validated data return res.json(validatedData); } catch (error) { @@ -804,19 +804,19 @@ actions: # Check 1: URL validation - pattern: "function\\s+(?:isValidUrl|validateUrl|checkUrl)\\s*\\([^)]*\\)\\s*\\{[^}]*new URL\\([^)]*\\)" message: "Using URL validation function with proper parsing." - + # Check 2: Domain allowlisting - pattern: "(?:allowlist|whitelist|allowed(?:Domain|Host))\\s*=\\s*\\[" message: "Implementing domain allowlisting for outbound requests." - + # Check 3: Private IP filtering - pattern: "(?:isPrivateIP|isInternalNetwork|blockInternalAddresses)" message: "Checking for and blocking private IP addresses." - + # Check 4: Protocol restriction - pattern: "(?:allowedProtocols|validProtocols)\\s*=\\s*\\[\\s*['\"]https?:['\"]" message: "Restricting URL protocols to HTTP/HTTPS only." - + # Check 5: Request timeout implementation - pattern: "timeout:\\s*\\d+" message: "Setting timeouts for outbound HTTP requests." @@ -847,4 +847,6 @@ metadata: - "https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.md" - "https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/07-Input_Validation_Testing/19-Server-Side_Request_Forgery" - "https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html#ssrf-protection" - +``` + + diff --git a/.cursor/rules/javascript-software-data-integrity-failures.mdc b/.cursor/rules/javascript-software-data-integrity-failures.mdc index 054508f..c593e77 100644 --- a/.cursor/rules/javascript-software-data-integrity-failures.mdc +++ b/.cursor/rules/javascript-software-data-integrity-failures.mdc @@ -4,7 +4,7 @@ globs: **/*.js, **/*.jsx, **/*.ts, **/*.tsx, !**/node_modules/**, !**/dist/**, ! --- # JavaScript Software and Data Integrity Failures (OWASP A08:2021) - +```yaml name: javascript_software_data_integrity_failures description: Detect and prevent software and data integrity failures in JavaScript applications as defined in OWASP Top 10:2021-A08 @@ -14,72 +14,72 @@ actions: # Pattern 1: Insecure Deserialization - pattern: "(?:JSON\\.parse|eval)\\s*\\((?:[^)]|\\n)*(?:localStorage|sessionStorage|document\\.cookie|location|window\\.name|fetch|axios|\\$\\.(?:get|post)|XMLHttpRequest)" message: "Insecure deserialization of user-controlled data detected. Validate and sanitize data before parsing JSON or using eval." - + # Pattern 2: Missing Subresource Integrity - pattern: "" negative_pattern: "integrity=['\"]sha(?:256|384|512)-[a-zA-Z0-9+/=]+" message: "Script tag without Subresource Integrity (SRI) hash. Add integrity and crossorigin attributes for third-party scripts." - + # Pattern 3: Insecure Package Installation - pattern: "(?:npm|yarn)\\s+(?:install|add)\\s+(?:[\\w@\\-\\.\\/:]+\\s+)*--no-(?:verify|integrity|signature)" message: "Package installation with integrity checks disabled. Always verify package integrity during installation." - + # Pattern 4: Insecure Object Deserialization - pattern: "(?:require|import)\\s+['\"](?:serialize-javascript|node-serialize|serialize|unserialize|deserialize)['\"]" message: "Using potentially unsafe serialization/deserialization libraries. Ensure proper validation and sanitization of serialized data." - + # Pattern 5: Missing Dependency Verification - pattern: "package\\.json" negative_pattern: "\"(?:scripts|devDependencies)\":\\s*{[^}]*\"(?:audit|verify|check)\":\\s*\"(?:npm|yarn)\\s+audit" file_pattern: "package\\.json$" message: "Missing dependency verification in package.json. Add npm/yarn audit to your scripts section." - + # Pattern 6: Insecure Dynamic Imports - pattern: "(?:import|require)\\s*\\(\\s*(?:variable|[a-zA-Z_$][a-zA-Z0-9_$]*|`[^`]*`|'[^']*'|\"[^\"]*\")\\s*\\)" negative_pattern: "(?:allowlist|whitelist|validate)" message: "Potentially insecure dynamic imports. Validate or restrict the modules that can be dynamically imported." - + # Pattern 7: Prototype Pollution - pattern: "Object\\.assign\\(\\s*(?:[^,]+)\\s*,\\s*(?:JSON\\.parse|req\\.body|req\\.query|req\\.params|formData\\.get)" message: "Potential prototype pollution vulnerability. Use Object.create(null) or sanitize objects before merging." - + # Pattern 8: Missing CI/CD Pipeline Integrity Checks - pattern: "(?:\\.github\\/workflows\\/|\\.gitlab-ci\\.yml|azure-pipelines\\.yml|Jenkinsfile)" negative_pattern: "(?:npm\\s+audit|yarn\\s+audit|checksum|integrity|verify|signature)" file_pattern: "(?:\\.github\\/workflows\\/.*\\.ya?ml|\\.gitlab-ci\\.yml|azure-pipelines\\.yml|Jenkinsfile)$" message: "Missing security checks in CI/CD pipeline. Add dependency scanning, integrity verification, and signature validation." - + # Pattern 9: Insecure Update Mechanism - pattern: "(?:update|upgrade|install)\\s*\\([^)]*\\)\\s*\\{[^}]*?\\}" negative_pattern: "(?:verify|checksum|hash|signature|integrity)" message: "Potentially insecure update mechanism. Implement integrity verification for all updates." - + # Pattern 10: Insecure Plugin Loading - pattern: "(?:plugin|addon|extension)\\.(?:load|register|install|add)\\s*\\([^)]*\\)" negative_pattern: "(?:verify|validate|checksum|hash|signature|integrity)" message: "Insecure plugin loading mechanism. Implement integrity verification for all plugins." - + # Pattern 11: Insecure Data Binding - pattern: "(?:eval|new\\s+Function|setTimeout|setInterval)\\s*\\(\\s*(?:[^,)]+\\.(?:value|innerHTML|innerText|textContent)|[^,)]+\\[[^\\]]+\\])" message: "Insecure data binding using eval or Function constructor. Use safer alternatives like JSON.parse or template literals." - + # Pattern 12: Insecure Object Property Assignment - pattern: "(?:Object\\.assign|\\{\\s*\\.\\.\\.)" negative_pattern: "Object\\.create\\(null\\)" message: "Potential prototype pollution in object assignment. Use Object.create(null) as the target object or sanitize inputs." - + # Pattern 13: Missing Lock File - pattern: "package\\.json" negative_pattern: "package-lock\\.json|yarn\\.lock" file_pattern: "package\\.json$" message: "Missing lock file for dependency management. Include package-lock.json or yarn.lock in version control." - + # Pattern 14: Insecure Webpack Configuration - pattern: "webpack\\.config\\.js" negative_pattern: "(?:integrity|sri|subresource|hash|checksum)" file_pattern: "webpack\\.config\\.js$" message: "Webpack configuration without integrity checks. Consider enabling SRI for generated assets." - + # Pattern 15: Insecure npm/yarn Configuration - pattern: "\\.npmrc|\\.yarnrc" negative_pattern: "(?:verify-store|integrity|signature)" @@ -89,14 +89,14 @@ actions: - type: suggest message: | **JavaScript Software and Data Integrity Failures Best Practices:** - + 1. **Secure Deserialization:** - Validate and sanitize data before deserialization - Use schema validation for JSON data - Example: ```javascript import Ajv from 'ajv'; - + // Define a schema for expected data const schema = { type: 'object', @@ -108,14 +108,14 @@ actions: required: ['id', 'name', 'role'], additionalProperties: false }; - + // Validate data before parsing function safelyParseJSON(data) { try { const parsed = JSON.parse(data); const ajv = new Ajv(); const validate = ajv.compile(schema); - + if (validate(parsed)) { return { valid: true, data: parsed }; } else { @@ -126,18 +126,18 @@ actions: } } ``` - + 2. **Subresource Integrity (SRI):** - Add integrity hashes to external scripts and stylesheets - Example: ```html - ``` - + ```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: "]*?integrity=['\"]sha(?:256|384|512)-[a-zA-Z0-9+/=]+['\"][^>]*?>" message: "Using Subresource Integrity (SRI) for external scripts." - + # Check 2: Dependency Verification - pattern: "\"scripts\":\\s*{[^}]*\"(?:audit|verify|check)\":\\s*\"(?:npm|yarn)\\s+audit" message: "Implementing dependency verification in package.json scripts." - + # Check 3: Lock File Usage - pattern: "(?:package-lock\\.json|yarn\\.lock)" file_pattern: "(?:package-lock\\.json|yarn\\.lock)$" message: "Using lock files for dependency management." - + # Check 4: Safe Object Creation - pattern: "Object\\.create\\(null\\)" message: "Using Object.create(null) to prevent prototype pollution." - + # Check 5: Schema Validation - pattern: "(?:ajv|joi|yup|zod|jsonschema|validate)" message: "Implementing schema validation for data integrity." @@ -659,4 +659,6 @@ metadata: - "https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/NPM_Security_Cheat_Sheet.md" - "https://cheatsheetseries.owasp.org/cheatsheets/Content_Security_Policy_Cheat_Sheet.html" - "https://owasp.org/www-community/attacks/Prototype_pollution" -
+``` + + diff --git a/.cursor/rules/javascript-standards.mdc b/.cursor/rules/javascript-standards.mdc index d5899fe..3238871 100644 --- a/.cursor/rules/javascript-standards.mdc +++ b/.cursor/rules/javascript-standards.mdc @@ -4,7 +4,7 @@ globs: *.js --- # JavaScript Development Standards - +```yaml name: javascript_standards description: Enforce JavaScript development standards for Drupal @@ -48,4 +48,5 @@ actions: metadata: priority: high version: 1.0 - +``` + diff --git a/.cursor/rules/javascript-vulnerable-outdated-components.mdc b/.cursor/rules/javascript-vulnerable-outdated-components.mdc index 381e90b..4434dc2 100644 --- a/.cursor/rules/javascript-vulnerable-outdated-components.mdc +++ b/.cursor/rules/javascript-vulnerable-outdated-components.mdc @@ -4,7 +4,7 @@ globs: **/*.js, **/*.jsx, **/*.ts, **/*.tsx, !**/node_modules/**, !**/dist/**, ! --- # JavaScript Vulnerable and Outdated Components (OWASP A06:2021) - +```yaml name: javascript_vulnerable_outdated_components description: Detect and prevent the use of vulnerable and outdated components in JavaScript applications as defined in OWASP Top 10:2021-A06 @@ -15,72 +15,72 @@ actions: - pattern: "\"(dependencies|devDependencies)\"\\s*:\\s*\\{[^}]*?\"([^\"]+)\"\\s*:\\s*\"\\^?([0-9]+\\.[0-9]+\\.[0-9]+)\"" location: "package\\.json$" message: "Check for outdated dependencies in package.json. Regularly update dependencies to avoid known vulnerabilities." - + # Pattern 2: Direct CDN Links Without Integrity Hashes - pattern: "]*(?!integrity=)" location: "\\.(html|js|jsx|ts|tsx)$" message: "CDN resources without integrity hashes. Add integrity and crossorigin attributes to script tags loading external resources." - + # Pattern 3: Hardcoded Library Versions in HTML - pattern: "]*>[^<]*?\"imports\"\\s*:\\s*\\{[^}]*?\"[^\"]+\"\\s*:\\s*\"https?://[^\"]+\"" negative_pattern: "integrity=" message: "Insecure import maps without integrity checks. Add integrity hashes to import map entries." - + # Pattern 15: Outdated Polyfills - pattern: "(?:core-js|@babel/polyfill|es6-promise|whatwg-fetch)" message: "Using potentially outdated polyfills. Consider using modern alternatives or feature detection." @@ -88,7 +88,7 @@ actions: - type: suggest message: | **JavaScript Vulnerable and Outdated Components Best Practices:** - + 1. **Dependency Management:** - Regularly update dependencies to their latest secure versions - Use tools like npm audit, Snyk, or Dependabot to detect vulnerabilities @@ -105,7 +105,7 @@ actions: } } ``` - + 2. **Lock Files:** - Always use lock files (package-lock.json, yarn.lock, or pnpm-lock.yaml) - Commit lock files to version control @@ -113,31 +113,31 @@ actions: ```bash # Generate a lock file if it doesn't exist npm install - + # Or for Yarn yarn - + # Or for pnpm pnpm install ``` - + 3. **Subresource Integrity:** - Use integrity hashes when loading resources from CDNs - Example: ```html - ``` - + 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 +``` + +