### Install drheaderplus using pip Source: https://github.com/garootman/drheaderplus/blob/main/README.md This command installs the drheaderplus package and its dependencies. Ensure you have Python 3.11+ installed. This is the standard way to install Python packages from PyPI. ```sh pip install drheaderplus ``` -------------------------------- ### GitHub Actions: Security Header Gate (YAML) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md Integrates DrHeaderPlus into GitHub Actions to block deployments based on security header configurations. It installs the tool, scans endpoints, and can generate JUnit reports for artifact upload. The CLI exits with code 70 on findings, failing the step. ```yaml # .github/workflows/security-headers.yml name: Security Header Audit on: push: branches: [main] pull_request: schedule: - cron: '0 6 * * 1' # Weekly Monday 6am jobs: audit-headers: runs-on: ubuntu-latest steps: - name: Install DrHeaderPlus run: pip install drheaderplus - name: Scan production endpoint run: drheader scan single https://your-app.example.com --output json - name: Scan with OWASP ASVS V14 preset run: drheader scan single https://your-app.example.com --preset owasp-asvs-v14 - name: Scan staging (allow self-signed certs) run: drheader scan single https://staging.example.com --verify false - name: Generate JUnit report if: always() run: drheader scan single https://your-app.example.com --junit - name: Upload JUnit report if: always() uses: actions/upload-artifact@v4 with: name: security-headers-junit path: reports/junit.xml ``` ```yaml - uses: actions/checkout@v4 - name: Install DrHeaderPlus run: pip install drheaderplus - name: Scan with custom rules merged with defaults run: drheader scan single https://your-app.example.com --rules-file custom_rules.yml --merge ``` -------------------------------- ### GitLab CI: Security Header Gate (YAML) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md Configures a GitLab CI job to audit security headers. It uses a Python Docker image, installs DrHeaderPlus, and scans a specified application URL. The job can also generate and report JUnit XML artifacts for findings. ```yaml # .gitlab-ci.yml security-headers: stage: test image: python:3.12-slim script: - pip install drheaderplus - drheader scan single $APP_URL --output json artifacts: when: always reports: junit: reports/junit.xml rules: - if: $CI_PIPELINE_SOURCE == "merge_request_event" - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH ``` ```yaml security-headers: stage: test image: python:3.12-slim script: - pip install drheaderplus - drheader scan single $APP_URL --junit artifacts: when: always reports: junit: reports/junit.xml ``` -------------------------------- ### Install Project Dependencies (Shell) Source: https://github.com/garootman/drheaderplus/blob/main/CONTRIBUTING.md Installs the necessary development dependencies for DrHeaderPlus using `uv`. The `--extra dev` flag ensures that development-specific packages are included. This command should be run after cloning the repository. ```shell uv sync --extra dev ``` -------------------------------- ### Pre-Deploy Security Header Gate Script (Python) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md A standalone Python script that scans a given URL for security header issues. It exits with a non-zero status code if high-severity findings are detected, making it suitable for CI/CD pipelines or manual pre-deploy checks. Requires the 'drheaderplus' package to be installed. ```python #!/usr/bin/env python3 """Pre-deploy security header gate. Exit 1 if high-severity issues found.""" import json import sys from drheader import Drheader URL = sys.argv[1] if len(sys.argv) > 1 else "https://your-app.example.com" scanner = Drheader(url=URL) findings = scanner.analyze() if not findings: print(f"PASS: {URL} — all security headers OK") sys.exit(0) high = [f for f in findings if f.severity == "high"] medium = [f for f in findings if f.severity == "medium"] print(f"SCAN: {URL} — {len(findings)} issues ({len(high)} high, {len(medium)} medium)") for f in findings: print(f" [{f.severity.upper()}] {f.rule}: {f.message}") if high: print(f"\nFAIL: {len(high)} high-severity issues — deploy blocked") sys.exit(1) else: print(f"\nWARN: {len(medium)} medium/low issues — deploy allowed") sys.exit(0) ``` -------------------------------- ### Programmatic Scanning and Filtering by Header Name (Python) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md Shows how to use Drheader to scan a URL and then filter the findings based on the header rule name. Examples include filtering for Content-Security-Policy and Set-Cookie related issues. ```python from drheader import Drheader scanner = Drheader(url="https://example.com") findings = scanner.analyze() csp_issues = [f for f in findings if f.rule.startswith("Content-Security-Policy")] cookie_issues = [f for f in findings if f.rule.startswith("Set-Cookie")] ``` -------------------------------- ### Programmatic Scanning and Filtering by Severity (Python) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md Demonstrates how to programmatically scan a URL using Drheader and then filter the resulting findings based on their severity level (high, medium, or low). This allows for granular control over which findings are processed. ```python from drheader import Drheader scanner = Drheader(url="https://example.com") findings = scanner.analyze() high = [f for f in findings if f.severity == "high"] medium = [f for f in findings if f.severity == "medium"] low = [f for f in findings if f.severity == "low"] print(f"High: {len(high)}, Medium: {len(medium)}, Low: {len(low)}") ``` -------------------------------- ### Load Custom Security Rules Without Merging (Python) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md Illustrates how to load custom security header rules from a file, completely replacing the default ruleset. When `merge_default` is not specified or is `False`, only the rules defined in the provided file will be used for analysis. ```python from drheader.utils import load_rules rules = load_rules(rules_file=open("strict_rules.yml")) # Only headers defined in strict_rules.yml are checked ``` -------------------------------- ### pytest: Assert No High-Severity Findings (Python) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md Demonstrates using DrHeaderPlus within pytest integration tests to validate security headers. It shows how to fail tests on any finding, only on high-severity findings, and how to parameterize tests for multiple endpoints. It also includes an example for checking OWASP ASVS V14 compliance. ```python # tests/test_security_headers.py from drheader import Drheader PRODUCTION_URL = "https://your-app.example.com" def test_no_security_header_issues(): """All security headers must pass default rules.""" scanner = Drheader(url=PRODUCTION_URL) findings = scanner.analyze() assert findings == [], f"Security header violations: {[f.to_dict() for f in findings]}" ``` ```python def test_no_high_severity_header_issues(): """No high-severity security header violations allowed.""" scanner = Drheader(url=PRODUCTION_URL) findings = scanner.analyze() high = [f for f in findings if f.severity == "high"] assert high == [], f"High-severity violations: {[f.to_dict() for f in high]}" ``` ```python import pytest from drheader import Drheader ENDPOINTS = [ "https://your-app.example.com", "https://your-app.example.com/api/health", "https://your-app.example.com/login", ] @pytest.mark.parametrize("url", ENDPOINTS) def test_security_headers(url): scanner = Drheader(url=url) findings = scanner.analyze() high = [f for f in findings if f.severity == "high"] assert high == [], f"{url}: {[f.to_dict() for f in high]}" ``` ```python from drheader import Drheader from drheader.utils import preset_rules def test_owasp_asvs_v14_compliance(): """Endpoint must pass OWASP ASVS V14 header requirements.""" rules = preset_rules("owasp-asvs-v14") scanner = Drheader(url="https://your-app.example.com") findings = scanner.analyze(rules=rules) assert findings == [], f"ASVS V14 violations: {[f.to_dict() for f in findings]}" ``` -------------------------------- ### Converting Security Findings to Dictionaries (Python) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md Demonstrates how to convert Drheader findings into Python dictionaries. This is useful for serialization, such as exporting to JSON, and provides a structured representation of each finding, omitting fields with `None` values. ```python from drheader import Drheader scanner = Drheader(url="https://example.com") findings = scanner.analyze() # Single finding to dict (omits None fields) finding_dict = findings[0].to_dict() # All findings to list of dicts all_dicts = [f.to_dict() for f in findings] ``` -------------------------------- ### Load Custom Security Rules from Remote URI (Python) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md Demonstrates loading custom security header rules from a remote URL (e.g., a GitHub Gist or repository). This allows for centralized management of security policies. The `merge_default=True` option includes default rules alongside the custom ones. ```python from drheader.utils import load_rules rules = load_rules( rules_uri="https://raw.githubusercontent.com/your-org/security-policy/main/headers.yml", merge_default=True, ) ``` -------------------------------- ### Load Compliance Presets with preset_rules() (Python) Source: https://context7.com/garootman/drheaderplus/llms.txt The `preset_rules()` function loads predefined security compliance rulesets, such as 'owasp-asvs-v14'. These presets replace any existing rules. The example demonstrates loading the ASVS preset, scanning a URL, and handling potential `ValueError` for invalid preset names. ```python from drheader import Drheader from drheader.utils import preset_rules # Load OWASP ASVS V14 preset rules = preset_rules("owasp-asvs-v14") # Scan with preset rules scanner = Drheader(url="https://example.com") findings = scanner.analyze(rules=rules) # ASVS V14 checks: CSP, HSTS, X-Content-Type-Options, X-Frame-Options, # Referrer-Policy, Access-Control-Allow-Origin for f in findings: print(f"[{f.severity.upper()}] {f.rule}: {f.message}") # Invalid preset raises ValueError try: rules = preset_rules("invalid-preset") except ValueError as e: print(f"Error: {e}") # Error: Unknown preset 'invalid-preset'. Available presets: owasp-asvs-v14 ``` -------------------------------- ### Bulk Scan URLs from JSON File (CLI) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md This CLI command demonstrates how to perform a bulk scan using a JSON file that specifies target URLs and optional request configurations. Each object in the JSON array can define a URL, HTTP method, timeout, and SSL verification settings. This provides granular control over multiple scan targets. ```json [ {"url": "https://app.example.com"}, {"url": "https://api.example.com", "method": "GET"}, {"url": "https://admin.example.com", "timeout": 15, "verify": false} ] ``` ```bash drheader scan bulk targets.json --output json ``` -------------------------------- ### Bulk Scan URLs from Text File (CLI) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md This CLI command shows how to perform a bulk scan of multiple URLs listed in a text file. The `--file-format txt` option specifies that the input file contains one URL per line. The `--output json` flag ensures the results are returned in JSON format, suitable for further processing. ```bash # urls.txt # https://app.example.com # https://api.example.com # https://admin.example.com drheader scan bulk urls.txt --file-format txt --output json ``` -------------------------------- ### Use POST Method Instead of HEAD (Python) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md This Python code demonstrates how to instruct Drheader to use the POST method instead of the default HEAD method for scanning headers. This is configured by setting the `method` parameter to "POST" during Drheader initialization. This can be necessary for certain APIs or endpoints that do not properly respond to HEAD requests. ```python from drheader import Drheader scanner = Drheader(url="https://api.example.com/health", method="POST") findings = scanner.analyze() ``` -------------------------------- ### Install drheaderplus using pip or uv Source: https://github.com/garootman/drheaderplus/blob/main/skills/drheaderplus-audit/SKILL.md Installs the drheaderplus package. This is a prerequisite for using the tool, either via CLI or programmatically. It requires Python 3.11 or higher. ```bash pip install drheaderplus # or with uv: uv pip install drheaderplus ``` -------------------------------- ### Load Custom Security Rules from File (Python) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md Shows how to load custom security header rules from a local YAML file and merge them with the default ruleset provided by Drheader. Custom rules can override existing defaults or add new checks. The `merge_default=True` argument ensures that default rules are included unless overridden. ```python from drheader import Drheader from drheader.utils import load_rules # Custom rules override defaults for matching headers, new ones are added rules = load_rules(rules_file=open("my_rules.yml"), merge_default=True) scanner = Drheader(url="https://example.com") findings = scanner.analyze(rules=rules) ``` -------------------------------- ### Harden CSP (YAML) Source: https://github.com/garootman/drheaderplus/blob/main/RULES.md Example configuration to harden Content Security Policy (CSP) by disallowing unsafe inline/eval/hashes and enforcing specific directives like Default-Src and Script-Src. ```yaml Content-Security-Policy: Required: True Must-Avoid: - unsafe-inline - unsafe-eval - unsafe-hashes Directives: Default-Src: Required: True Must-Contain: 'https:' Script-Src: Required: True Value: self ``` -------------------------------- ### Perform OWASP ASVS V14 Compliance Check (CLI) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md These CLI commands demonstrate how to perform an OWASP ASVS V14 compliance check using DrHeaderPlus. The first command performs a standard scan, while the second specifies JSON output for programmatic processing. This is a quick way to verify compliance without writing code. ```bash drheader scan single --preset owasp-asvs-v14 https://example.com drheader scan single --preset owasp-asvs-v14 --output json https://example.com ``` -------------------------------- ### Test Pre-captured Headers (Python) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md Validates security headers captured from a staging deploy without making network requests. It initializes Drheader with a dictionary of headers and asserts that no high-severity findings are returned. ```python from drheader import Drheader def test_required_headers_present(): """Validate headers captured from a staging deploy.""" headers = { "Content-Security-Policy": "default-src 'self'; script-src 'self'", "Strict-Transport-Security": "max-age=31536000; includeSubDomains", "X-Content-Type-Options": "nosniff", "X-Frame-Options": "DENY", "Referrer-Policy": "strict-origin-when-cross-origin", } scanner = Drheader(headers=headers) findings = scanner.analyze() high = [f for f in findings if f.severity == "high"] assert high == [], f"Violations: {[f.to_dict() for f in high]}" ``` -------------------------------- ### Accessing Security Finding Fields (Python) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md Illustrates how to iterate through the findings returned by Drheader and access individual fields for each finding, such as rule name, message, severity, value, expected value, and values to avoid. This provides detailed information about each security header issue. ```python from drheader import Drheader scanner = Drheader(url="https://example.com") findings = scanner.analyze() for f in findings: print(f"Rule: {f.rule}") print(f"Message: {f.message}") print(f"Severity: {f.severity}") if f.value: print(f"Value: {f.value}") if f.expected: print(f"Expected: {f.expected}") if f.avoid: print(f"Avoid: {f.avoid}") print() ``` -------------------------------- ### Scan Behind Authentication with Custom Cookies (Python) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md This Python code shows how to scan a URL that requires authentication using custom cookies. The cookies are provided as a dictionary to the `cookies` parameter when creating the Drheader instance. This is useful for sites that rely on session cookies for authentication. ```python from drheader import Drheader scanner = Drheader( url="https://app.example.com/dashboard", cookies={"session_id": "abc123", "csrf_token": "xyz789"}, ) findings = scanner.analyze() ``` -------------------------------- ### JSON Export for Security Header Reports (Python) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md Generates a comprehensive security header report in JSON format for a given URL. The report includes summary statistics (total findings, counts by severity) and a detailed list of all findings, each converted to a dictionary. This JSON output is suitable for dashboards or further analysis. ```python import json from drheader import Drheader scanner = Drheader(url="https://example.com") findings = scanner.analyze() report = { "url": "https://example.com", "total": len(findings), "high": len([f for f in findings if f.severity == "high"]), "medium": len([f for f in findings if f.severity == "medium"]), "low": len([f for f in findings if f.severity == "low"]), "passed": len(findings) == 0, "findings": [f.to_dict() for f in findings], } with open("security_headers_report.json", "w") as f: json.dump(report, f, indent=2) ``` -------------------------------- ### Scan Behind Authentication with Bearer Token (Python) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md This Python code demonstrates how to scan a URL that requires authentication using a Bearer token. The token is passed in the `headers` dictionary when initializing the Drheader object. This is common for API authentication where tokens are provided in the Authorization header. ```python from drheader import Drheader scanner = Drheader( url="https://api.example.com/protected", headers={"Authorization": "Bearer eyJhbGciOiJIUzI1NiIs..."}, ) findings = scanner.analyze() ``` -------------------------------- ### Sample DrHeaderPlus Security Policy (YAML) Source: https://github.com/garootman/drheaderplus/blob/main/RULES.md An example of a DrHeaderPlus policy file in YAML format. This policy defines rules for Cache-Control, Content-Security-Policy, Referrer-Policy, Server, Set-Cookie, X-Frame-Options, and X-XSS-Protection headers. ```yaml Cache-Control: Required: True Value: - no-store - max-age=0 Content-Security-Policy: Required: True Must-Avoid: - block-all-mixed-content - referrer - unsafe-inline - unsafe-eval Directives: Default-Src: Required: True Value-One-Of: - none - self Severity: Critical Report-To: Required: Optional Value: /_/csp_report Referrer-Policy: Required: True Value-One-Of: - no-referrer - same-origin - strict-origin Server: Required: False Severity: Warning Set-Cookie: Required: Optional Must-Contain: - HttpOnly - Secure Must-Contain-One: - Expires - Max-Age X-Frame-Options: Required: True Value-One-Of: - DENY - SAMEORIGIN X-XSS-Protection: Required: True Value: 0 ``` -------------------------------- ### Enforce Exact Content-Security-Policy Value (YAML) Source: https://github.com/garootman/drheaderplus/blob/main/RULES.md This example enforces an exact value for the 'Content-Security-Policy' header. It specifies a complete policy string, including keywords like 'none' and 'self', with their quotation marks intact as required for exact value matching. ```yaml Content-Security-Policy: Required: True Value: default-src 'none'; script-src 'self'; style-src 'unsafe-inline' ``` -------------------------------- ### Pass custom headers to DrHeaderPlus scanner Source: https://github.com/garootman/drheaderplus/blob/main/README.md This Python example illustrates how to provide custom HTTP headers, such as an API key, when creating a Drheader instance. This is useful for authenticated requests or specific testing scenarios. ```python from drheader import Drheader scanner = Drheader(url='https://example.com', headers={'X-API-Key': '726204fe-8a3a-4478-ae8f-4fb216a8c4ba'}) ``` -------------------------------- ### Prevent Caching (YAML) Source: https://github.com/garootman/drheaderplus/blob/main/RULES.md Example rules to prevent caching by setting specific values for Cache-Control and Pragma headers. ```yaml Cache-Control: Required: True Value: - no-store - max-age=0 Pragma: Required: True Value: no-cache ``` -------------------------------- ### Skip SSL Verification (Python) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md This Python code snippet demonstrates how to skip SSL certificate verification when scanning a URL. This is achieved by setting the `verify` parameter to `False` during Drheader initialization. It's typically used for internal or staging environments with self-signed certificates, but should be used with caution in production. ```python from drheader import Drheader scanner = Drheader(url="https://staging.internal.example.com", verify=False) findings = scanner.analyze() ``` -------------------------------- ### Validate Custom Headers with Delimiters (JSON) Source: https://github.com/garootman/drheaderplus/blob/main/RULES.md Example JSON data demonstrating the structure of a custom header that would be validated by the preceding YAML configuration. ```json { "X-Custom-Header": "item_1 = value_1, value_2; item_2 = value_1; item_3" } ``` -------------------------------- ### Check for Directive Presence/Absence in Content-Security-Policy (YAML) Source: https://github.com/garootman/drheaderplus/blob/main/RULES.md This example demonstrates how to check for the presence or absence of directives at the header level for 'Content-Security-Policy'. It requires 'default-src' to be present and 'frame-src' to be absent. ```yaml Content-Security-Policy: Required: True Must-Contain: - default-src Must-Avoid: - frame-src ``` -------------------------------- ### Load Built-in Ruleset with default_rules() (Python) Source: https://context7.com/garootman/drheaderplus/llms.txt The `default_rules()` function from `drheader.utils` loads the built-in security header ruleset. This function is automatically used by `Drheader.analyze()` if no other rules are provided. The example shows how to load, inspect, and explicitly pass these rules to the scanner. ```python from drheader import Drheader from drheader.utils import default_rules # Load default rules (automatically used if no rules passed to analyze()) rules = default_rules() # Inspect available rules for header_name in rules: print(f"Header: {header_name}") print(f" Required: {rules[header_name].get('Required')}") if 'Value' in rules[header_name]: print(f" Value: {rules[header_name]['Value']}") if 'Must-Avoid' in rules[header_name]: print(f" Must-Avoid: {rules[header_name]['Must-Avoid']}") # Explicitly pass default rules to analyze scanner = Drheader(url="https://example.com") findings = scanner.analyze(rules=rules) ``` -------------------------------- ### Scan Multiple URLs Programmatically (Python) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md This Python code snippet shows how to scan multiple URLs programmatically using the Drheader library. It iterates through a list of URLs, creates a Drheader instance for each, analyzes its headers, and prints a status indicating whether the scan passed or failed based on findings. This is useful for integrating header scanning into larger Python applications. ```python from drheader import Drheader urls = [ "https://app.example.com", "https://api.example.com", "https://admin.example.com", ] for url in urls: scanner = Drheader(url=url) findings = scanner.analyze() status = "PASS" if not findings else f"FAIL ({len(findings)} issues)" print(f"{url}: {status}") ``` -------------------------------- ### Enforce Specific Values for Clear-Site-Data Header (YAML) Source: https://github.com/garootman/drheaderplus/blob/main/RULES.md This example demonstrates enforcing specific values for the 'Clear-Site-Data' header. It requires the header to be present and its value to be one of the specified options ('cache', 'storage'). Quotation marks around values must be omitted. ```yaml Clear-Site-Data: Required: True Value: - cache - storage ``` -------------------------------- ### Perform OWASP ASVS V14 Compliance Check (Python) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md This Python code uses the Drheader library to perform an OWASP ASVS V14 compliance check on a given URL. It loads the preset rules for ASVS V14 and analyzes the headers, printing any findings with their severity and message. This is useful for automated security assessments against OWASP standards. ```python from drheader import Drheader from drheader.utils import preset_rules rules = preset_rules("owasp-asvs-v14") scanner = Drheader(url="https://example.com") findings = scanner.analyze(rules=rules) for f in findings: print(f"[{f.severity.upper()}] {f.rule}: {f.message}") ``` -------------------------------- ### GitHub Actions Workflow for Security Header Audit Source: https://context7.com/garootman/drheaderplus/llms.txt This GitHub Actions workflow automates the security header audit using DrHeaderPlus. It checks out the code, installs the tool, and runs scans against specified URLs with various configurations, including presets and custom rules. It also includes steps to generate and upload JUnit reports. ```yaml name: Security Header Audit on: push: branches: [main] pull_request: schedule: - cron: '0 6 * * 1' # Weekly Monday 6am jobs: audit-headers: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install DrHeaderPlus run: pip install drheaderplus - name: Scan production endpoint run: drheader scan single https://your-app.example.com --output json - name: Scan with OWASP ASVS V14 preset run: drheader scan single https://your-app.example.com --preset owasp-asvs-v14 - name: Scan with custom rules merged with defaults run: drheader scan single https://your-app.example.com --rules-file custom_rules.yml --merge - name: Scan staging (allow self-signed certs) run: drheader scan single https://staging.example.com --verify false - name: Generate JUnit report if: always() run: drheader scan single https://your-app.example.com --junit - name: Upload JUnit report if: always() uses: actions/upload-artifact@v4 with: name: security-headers-junit path: reports/junit.xml ``` -------------------------------- ### Load Custom Rulesets with load_rules() (Python) Source: https://context7.com/garootman/drheaderplus/llms.txt The `load_rules()` function allows loading custom security header rules from a local file or a remote URI. These custom rules can either completely replace the default rules or be merged with them, with custom rules taking precedence. The example shows loading from a file and a URI, and provides a sample YAML structure for custom rules. ```python from drheader import Drheader from drheader.utils import load_rules # Load custom rules from file (replace defaults entirely) with open("custom_rules.yml") as f: rules = load_rules(rules_file=f) # Load custom rules and merge with defaults (custom rules override matching defaults) with open("custom_rules.yml") as f: rules = load_rules(rules_file=f, merge_default=True) # Load custom rules from remote URI rules = load_rules( rules_uri="https://raw.githubusercontent.com/your-org/security-policy/main/headers.yml", merge_default=True, ) # Use custom rules for analysis scanner = Drheader(url="https://example.com") findings = scanner.analyze(rules=rules) # Example custom_rules.yml: # Content-Security-Policy: # Required: True # Must-Avoid: # - unsafe-inline # - unsafe-eval # Directives: # Default-Src: # Required: True # Value-One-Of: # - none # - self # # Strict-Transport-Security: # Required: True # Must-Contain: # - includeSubDomains # Directives: # max-age: # Required: True # Value-Gte: 31536000 ``` -------------------------------- ### Set Custom Timeout for Scan (Python) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md This Python code shows how to configure a custom timeout for an HTTP request when scanning headers. The `timeout` parameter is set to the desired number of seconds (e.g., 30) during Drheader initialization. This is useful for endpoints that may respond slowly. ```python from drheader import Drheader scanner = Drheader(url="https://slow-endpoint.example.com", timeout=30) findings = scanner.analyze() ``` -------------------------------- ### Define Custom Header Scan Rules (YAML) Source: https://github.com/garootman/drheaderplus/blob/main/examples/EXAMPLES.md This snippet shows how to define custom rules for scanning HTTP headers using YAML format. It allows specifying required headers, directives to avoid or contain, and custom header checks with severity levels. This is useful for enforcing specific security policies beyond built-in checks. ```yaml # my_rules.yml — override CSP and add a custom header check Content-Security-Policy: Required: True Must-Avoid: - unsafe-inline - unsafe-eval Directives: Default-Src: Required: True Value-One-Of: - none - self Script-Src: Required: True Must-Avoid: - unsafe-inline # Enforce a stricter HSTS max-age (1 year) Strict-Transport-Security: Required: True Must-Contain: - includeSubDomains - preload Directives: max-age: Required: True Value-Gte: 31536000 # Flag a custom internal header that should not leak X-Internal-Debug: Required: False Severity: high ``` -------------------------------- ### Load security rules for DrHeaderPlus Source: https://github.com/garootman/drheaderplus/blob/main/llms.txt Demonstrates various methods to load security rules for DrHeaderPlus, including built-in defaults, preset configurations like 'owasp-asvs-v14', and custom rules from local YAML files or remote URIs. Custom rules can be merged with defaults. ```python from drheader.utils import default_rules, preset_rules, load_rules # Built-in defaults rules = default_rules() # OWASP ASVS V14 compliance preset rules = preset_rules("owasp-asvs-v14") # Custom YAML file, merged with defaults rules = load_rules(rules_file=open("my_rules.yml"), merge_default=True) # Custom YAML from a remote URI rules = load_rules(rules_uri="https://example.com/rules.yml", merge_default=True) ``` -------------------------------- ### Basic DrHeaderPlus analysis in Python Source: https://github.com/garootman/drheaderplus/blob/main/README.md This Python snippet demonstrates how to initialize the Drheader class and perform a basic analysis of HTTP headers. It shows how to pass custom headers to the scanner. ```python from drheader import Drheader scanner = Drheader(headers={'X-XSS-Protection': '1; mode=block'}) report = scanner.analyze() ``` -------------------------------- ### Run DrHeaderPlus Scan with OWASP ASVS Preset (CLI) Source: https://github.com/garootman/drheaderplus/blob/main/RULES.md This command initiates a security scan of a given URL using the 'owasp-asvs-v14' preset ruleset. It's a direct way to check a live website against specific compliance requirements. ```shell drheader scan single --preset owasp-asvs-v14 https://example.com ``` -------------------------------- ### Clone DrHeaderPlus Repository (Shell) Source: https://github.com/garootman/drheaderplus/blob/main/CONTRIBUTING.md Clones the DrHeaderPlus repository from GitHub to your local machine. Replace `` with your actual GitHub username. This is the first step in setting up the project for local development. ```shell git clone git@github.com:/DrHeaderPlus.git ``` -------------------------------- ### Compare Headers with OWASP ASVS Preset (CLI) Source: https://github.com/garootman/drheaderplus/blob/main/RULES.md This command compares a local header file against the 'owasp-asvs-v14' preset ruleset. It's useful for analyzing pre-saved headers or testing configurations offline. ```shell drheader compare single --preset owasp-asvs-v14 headers.json ``` -------------------------------- ### Run Checks and Tests (Shell) Source: https://github.com/garootman/drheaderplus/blob/main/CONTRIBUTING.md Executes the project's checks and tests using the `make check` command. This ensures that your changes comply with project standards and that all tests are passing before committing. It is recommended to run this command after making code modifications. ```shell make check ``` -------------------------------- ### Commit and Push Changes (Shell) Source: https://github.com/garootman/drheaderplus/blob/main/CONTRIBUTING.md Stages all changes, commits them with a descriptive message, and pushes the branch to the remote repository. Replace `` with a concise summary of your modifications. This is the final step before submitting a pull request. ```shell git add . git commit -m '' git push origin ``` -------------------------------- ### Run DrHeaderPlus Scan with OWASP ASVS Preset (Python) Source: https://github.com/garootman/drheaderplus/blob/main/RULES.md This Python code snippet demonstrates how to use DrHeaderPlus programmatically to analyze a URL with the 'owasp-asvs-v14' preset. It loads the preset rules and then performs the analysis. ```python from drheader import Drheader from drheader.utils import preset_rules rules = preset_rules("owasp-asvs-v14") report = Drheader(url="https://example.com").analyze(rules=rules) ``` -------------------------------- ### CI/CD Integration with DrHeaderPlus CLI Source: https://github.com/garootman/drheaderplus/blob/main/llms.txt Shows how to integrate DrHeaderPlus into a CI/CD pipeline, such as GitHub Actions. The CLI's non-zero exit code (70) upon finding issues can act as a gate. It also demonstrates generating JUnit XML reports for CI integration. ```yaml # GitHub Actions - run: pip install drheaderplus - run: drheader scan single https://your-app.example.com --preset owasp-asvs-v14 ``` ```bash drheader scan single https://example.com --junit # Creates reports/junit.xml ``` -------------------------------- ### Access and Convert Finding Details with Finding Dataclass (Python) Source: https://context7.com/garootman/drheaderplus/llms.txt Illustrates how to access individual security header analysis results using the Finding dataclass. It shows how to retrieve details like rule, message, severity, and contextual values, and how to convert findings to dictionaries for serialization or filtering. ```python from drheader import Drheader scanner = Drheader(url="https://example.com") findings = scanner.analyze() for finding in findings: # Access Finding fields directly (Finding is a dataclass, NOT a dict) print(f"Rule: {finding.rule}") # Header or directive name print(f"Message: {finding.message}") # Human-readable error message print(f"Severity: {finding.severity}") # "high", "medium", or "low" if finding.value: print(f"Value: {finding.value}") # Observed header value if finding.expected: print(f"Expected: {finding.expected}") # List of expected values if finding.avoid: print(f"Avoid: {finding.avoid}") # List of disallowed values if finding.anomalies: print(f"Anomalies: {finding.anomalies}") # Unexpected items found if finding.delimiter: print(f"Delimiter: {finding.delimiter}") # Value separator character print() # Convert single finding to dict (omits None fields) finding_dict = findings[0].to_dict() # {'rule': 'Cache-Control', 'message': 'Value does not match security policy', # 'severity': 'high', 'value': 'max-age=604800', 'expected': ['no-store', 'max-age=0'], # 'delimiter': ','} # Convert all findings to list of dicts for JSON export all_dicts = [f.to_dict() for f in findings] # Filter findings by severity high_severity = [f for f in findings if f.severity == "high"] medium_severity = [f for f in findings if f.severity == "medium"] ``` -------------------------------- ### Create Development Branch (Shell) Source: https://github.com/garootman/drheaderplus/blob/main/CONTRIBUTING.md Creates a new Git branch for local development. This is a standard practice to isolate changes for bug fixes or new features. Replace `` with a descriptive name for your branch. ```shell git checkout -b ``` -------------------------------- ### Analyze HTTP security headers using DrHeaderPlus Python library Source: https://github.com/garootman/drheaderplus/blob/main/llms.txt Initializes the Drheader scanner with a URL and analyzes its HTTP security headers. The analyze() method returns a list of findings, each containing severity, rule, and message details. An empty list indicates all headers passed. ```python from drheader import Drheader scanner = Drheader(url="https://example.com") findings = scanner.analyze() for f in findings: print(f"[{f.severity.upper()}] {f.rule}: {f.message}") ``` -------------------------------- ### Piping JSON Output to jq for Processing Source: https://github.com/garootman/drheaderplus/blob/main/CLI.md This command shows how to pipe the JSON output from DrHeaderPlus directly to the jq command-line JSON processor. This allows for powerful filtering, transformation, and pretty-printing of scan results. ```sh drheader scan single --output json https://example.com | jq '.' ``` -------------------------------- ### Scan Remote URLs and Analyze Headers with Drheader Class (Python) Source: https://context7.com/garootman/drheaderplus/llms.txt Demonstrates how to use the Drheader class to scan remote URLs or analyze pre-captured headers. It covers various request customizations like HTTP methods, headers, timeouts, SSL verification, and cross-origin isolation checks. The output findings can be processed or converted to dictionaries. ```python from drheader import Drheader # Scan a remote URL (default: HEAD request) scanner = Drheader(url="https://example.com") findings = scanner.analyze() # Scan with custom HTTP method scanner = Drheader(url="https://example.com", method="POST") findings = scanner.analyze() # Scan with custom request headers (e.g., authentication) scanner = Drheader( url="https://api.example.com/protected", headers={"Authorization": "Bearer eyJhbGciOiJIUzI1NiIs..."}, ) findings = scanner.analyze() # Scan with custom timeout and disabled SSL verification scanner = Drheader(url="https://staging.example.com", timeout=30, verify=False) findings = scanner.analyze() # Analyze pre-captured headers without network request headers = { "Content-Security-Policy": "default-src 'self'; script-src 'self'", "Strict-Transport-Security": "max-age=31536000; includeSubDomains", "X-Content-Type-Options": "nosniff", "X-Frame-Options": "DENY", "Referrer-Policy": "strict-origin-when-cross-origin", } scanner = Drheader(headers=headers) findings = scanner.analyze() # Enable cross-origin isolation checks (COEP/COOP) scanner = Drheader(url="https://example.com") findings = scanner.analyze(cross_origin_isolated=True) # Process findings for f in findings: print(f"[{f.severity.upper()}] {f.rule}: {f.message}") if f.expected: print(f" Expected: {f.expected}") # Convert findings to JSON-serializable dicts finding_dicts = [f.to_dict() for f in findings] # Output: # [HIGH] Content-Security-Policy: Header not included in response # [HIGH] Cache-Control: Value does not match security policy # Expected: ['no-store', 'max-age=0'] ``` -------------------------------- ### Scan URLs in Bulk with drheader CLI Source: https://context7.com/garootman/drheaderplus/llms.txt The `drheader scan bulk` command scans multiple URLs from a file. It supports both plain text files with one URL per line and JSON files for advanced per-target configuration, including custom HTTP methods, headers, timeouts, and SSL settings. Preset rules can also be applied to all targets. ```bash # Scan from text file (one URL per line) drheader scan bulk urls.txt --file-format txt # Scan from JSON file with per-target config drheader scan bulk targets.json --output json # Use preset for all targets drheader scan bulk targets.json --preset owasp-asvs-v14 # Example urls.txt: # https://app.example.com # https://api.example.com # https://admin.example.com # Example targets.json: # [ # {"url": "https://app.example.com"}, # {"url": "https://api.example.com", "method": "GET"}, # {"url": "https://admin.example.com", "timeout": 15, "verify": false} # ] ``` -------------------------------- ### Pytest Integration for Security Header Tests Source: https://context7.com/garootman/drheaderplus/llms.txt DrHeaderPlus integrates with pytest for automated security header testing within integration test suites. These tests can verify all headers against default rules, filter findings by severity, or check specific endpoints using custom rule sets. The `Drheader` class and `preset_rules` utility are used for this integration. ```python # tests/test_security_headers.py import pytest from drheader import Drheader from drheader.utils import preset_rules PRODUCTION_URL = "https://your-app.example.com" def test_no_security_header_issues(): """All security headers must pass default rules.""" scanner = Drheader(url=PRODUCTION_URL) findings = scanner.analyze() assert findings == [], f"Security header violations: {[f.to_dict() for f in findings]}" def test_no_high_severity_header_issues(): """No high-severity security header violations allowed.""" scanner = Drheader(url=PRODUCTION_URL) findings = scanner.analyze() high = [f for f in findings if f.severity == "high"] assert high == [], f"High-severity violations: {[f.to_dict() for f in high]}" def test_owasp_asvs_v14_compliance(): """Endpoint must pass OWASP ASVS V14 header requirements.""" rules = preset_rules("owasp-asvs-v14") scanner = Drheader(url=PRODUCTION_URL) findings = scanner.analyze(rules=rules) assert findings == [], f"ASVS V14 violations: {[f.to_dict() for f in findings]}" # Test multiple endpoints with parametrize ENDPOINTS = [ "https://your-app.example.com", "https://your-app.example.com/api/health", "https://your-app.example.com/login", ] @pytest.mark.parametrize("url", ENDPOINTS) def test_security_headers_multiple_endpoints(url): scanner = Drheader(url=url) findings = scanner.analyze() high = [f for f in findings if f.severity == "high"] assert high == [], f"{url}: {[f.to_dict() for f in high]}" ``` -------------------------------- ### CLI - drheader scan single (Bash) Source: https://context7.com/garootman/drheaderplus/llms.txt The `drheader scan single` command-line interface provides a way to scan a single URL for security header issues. It supports various output formats (table, JSON, JUnit XML), rule loading options (presets, custom files), and request customization (method, timeout, verification, parameters, body). The CLI exits with code 70 if findings are present, suitable for CI/CD. ```bash # Basic scan (table output) drheader scan single https://example.com # JSON output for programmatic processing drheader scan single --output json https://example.com # Use OWASP ASVS V14 preset drheader scan single --preset owasp-asvs-v14 https://example.com # Use custom rules file merged with defaults drheader scan single --rules-file custom_rules.yml --merge https://example.com # Enable cross-origin isolation checks drheader scan single --cross-origin-isolated https://example.com # Generate JUnit XML report (saved to reports/junit.xml) drheader scan single --junit https://example.com # Custom HTTP method drheader scan single https://example.com --method POST # Custom timeout and skip SSL verification drheader scan single https://staging.example.com --timeout 30 --verify false # Send request parameters drheader scan single https://example.com --params '{"key": "value"}' # Send JSON body drheader scan single https://example.com --json '{"data": "payload"}' # Output example (table format): # https://example.com: 9 issues found # ---- # rule | Cache-Control ``` -------------------------------- ### Compare Multiple Header Sets with drheader CLI Source: https://context7.com/garootman/drheaderplus/llms.txt The `drheader compare bulk` command validates multiple sets of pre-captured headers from a JSON file. Each entry in the file associates a URL identifier with a set of headers to validate. Options include using presets and specifying JSON output. ```bash # Validate multiple header sets drheader compare bulk headers_bulk.json # With preset rules drheader compare bulk --preset owasp-asvs-v14 headers_bulk.json # JSON output drheader compare bulk --output json headers_bulk.json # Example headers_bulk.json: # [ # { # "url": "https://example.com", # "headers": { # "Cache-Control": "private, must-revalidate", # "Content-Security-Policy": "default-src 'self'; script-src 'unsafe-inline'" # } # }, # { # "url": "https://example.net", # "headers": { # "Referrer-Policy": "strict-origin", # "Strict-Transport-Security": "max-age=31536000; preload", # "X-Content-Type-Options": "nosniff" # } # } # ] ``` -------------------------------- ### Compare Single Header Set with drheader CLI Source: https://context7.com/garootman/drheaderplus/llms.txt The `drheader compare single` command validates pre-captured headers from a JSON file without making network requests. This is useful for analyzing headers from staging environments or validating configurations before deployment. It supports presets, custom rules files, and JSON output. ```bash # Validate headers from JSON file drheader compare single headers.json # Use OWASP ASVS V14 preset drheader compare single --preset owasp-asvs-v14 headers.json # Use custom rules drheader compare single --rules-file custom_rules.yml headers.json # JSON output drheader compare single --output json headers.json # Example headers.json: # { # "Content-Security-Policy": "default-src 'self'; script-src 'self'", # "Strict-Transport-Security": "max-age=31536000; includeSubDomains", # "X-Content-Type-Options": "nosniff", # "X-Frame-Options": "DENY", # "Referrer-Policy": "strict-origin-when-cross-origin" # } ```