From c1b6d1b9daf3ee25be8d273ca6676210ff766916 Mon Sep 17 00:00:00 2001 From: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> Date: Fri, 31 Jul 2026 01:50:09 +0100 Subject: [PATCH 1/2] Fixes for the security and quality issues reported. (#223) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: add skeleton files and requirements * fix: remove embedded git repo * Core Structure Created * feat: build complete core — scanner engine, 10 rules, API, playbooks, compliance mappings, docs * docs: replace ASCII architecture with interactive Mermaid diagram * feat: Sentinel integration — ingest.py, 4 KQL rules, setup guide (#12) * feat: add sentinel/ingest.py — Log Analytics ingestion via HMAC-SHA256 * feat: add sentinel/__init__.py * feat: add KQL rule — HIGH severity finding detected * feat: add KQL rule — misconfiguration wave detection * feat: add KQL rule — new resource type critical detection * Delete sentinel/rules directory * Create rules * Delete sentinel/rules * Add KQL rule for high severity findings * Add Misconfiguration Wave detection rule * Add KQL rule for persistent misconfiguration detection * Add KQL rule for new critical resource types This rule identifies new resource types with critical findings that have occurred in the last 24 hours, excluding known types from the last 30 days. * Add script to generate test findings in JSON format This script generates test findings related to security compliance and saves them in a JSON file. * Add Sentinel integration test plan and results Added a comprehensive test plan for Sentinel integration, detailing test objectives, results, and acceptance criteria for various KQL rules and data ingestion. * docs: add sentinel integration setup guide Added a comprehensive setup guide for integrating Sentinel with Azure, covering prerequisites, workspace creation, activation, environment variable setup, ingestion, log verification, KQL rules deployment, and incident verification. * fix: add AZ-STOR-003 compliance mappings, correct NIST control to PR.DS-3 * docs: add real-world breach scenarios for all 10 starter rules (#15) * feat: add AZ-KV-002 key vault public access rule and remediation playbook (#14) * docs: update README with rule count, roadmap progress and contributors * feat: add network security rules AZ-NET-003 to AZ-NET-010 (#16) * Add az_net_003.py to check NSG rules for port 443 This script detects Network Security Groups (NSGs) with unrestricted inbound access on port 443 and provides remediation guidance. * Add AZ-NET-004 rule for empty NSG detection This script detects Network Security Groups (NSGs) that have no custom security rules configured, providing details for remediation. * Add AZ-NET-005 rule for DDoS protection check This script detects virtual networks in Azure that do not have DDoS protection enabled and provides remediation steps. * feat: add rule AZ-NET-006 — public IP unassociated with any resource This rule detects public IP addresses that are not associated with any resource, providing details for remediation. * feat: add rule AZ-NET-007 — Application Gateway without WAF enabled This rule detects Application Gateways that do not have WAF enabled, logging findings and providing remediation steps. * feat: add rule AZ-NET-008 — load balancer with no backend pool This rule detects load balancers in Azure that are not configured with a backend pool, indicating potential misconfiguration or unnecessary costs. * feat: add rule AZ-NET-009 — VPN gateway using outdated IKE version This script detects VPN gateways using the outdated IKEv1 protocol and provides remediation steps to migrate to IKEv2. * feat: add rule AZ-NET-010 — subnet with no NSG attached This script detects subnets in Azure that do not have a Network Security Group (NSG) attached, logging findings and providing remediation guidance. * feat: add playbook fix_az_net_003.sh This script updates the NSG rule to restrict inbound traffic on port 443 to a specified IP range. * feat: add playbook fix_az_net_004.sh This script adds a default deny-all inbound rule to a specified NSG. * feat: add playbook fix_az_net_005.sh This script enables DDoS protection on a specified virtual network in Azure. It checks for required parameters and provides usage instructions if they are missing. * feat: add playbook fix_az_net_006.sh This script deletes unassociated public IP addresses in Azure. * feat: add playbook fix_az_net_007.sh This script enables WAF on an Application Gateway, ensuring compliance with the AZ-NET-007 rule. * feat: add playbook fix_az_net_008.sh Script to remediate AZ-NET-008 by deleting empty load balancers. * feat:add script to update VPN connection to IKEv2 This script updates a VPN connection to use IKEv2, ensuring compliance with the AZ-NET-009 rule. * feat: add playbook fix_az_net_010.sh This script attaches a specified network security group to a given subnet in a virtual network, ensuring compliance with the AZ-NET-010 rule. * Clarify description and add note for public-facing services Updated the description to clarify the risk of exposing port 443 and added a note regarding public-facing services. * Change severity level from MEDIUM to HIGH * fix: AZ-NET-005 severity changed to LOW — DDoS Standard high cost on small subscriptions * Add note about NetworkManagementClient usage Added a note regarding the creation of NetworkManagementClient directly and suggested a follow-up for consistency. * Add note about NetworkManagementClient usage Added a note regarding the use of NetworkManagementClient and suggested a follow-up for consistency. * Add additional security controls to CIS Azure benchmark * Refine control descriptions in nist_csf.json Updated descriptions for various controls to enhance clarity and specificity regarding remote access management, data protection, and security measures. * fix: add AZ-NET-003 to AZ-NET-010 to ISO27001 compliance framework Updated descriptions for various controls to clarify compliance requirements and improve security guidance. --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> * Feat/az stor 003 (#21) * feat: add rule AZ-STOR-003 storage lifecycle policy check * feat: add rule AZ-STOR-003 storage lifecycle policy check * docs: add SOC 2 Type II compliance framework mapping (#33) * docs: add SOC 2 Type II compliance framework mapping for all 20 rules Added SOC 2 Type II framework with detailed controls for security measures and compliance requirements. * feat: add soc2 to FRAMEWORK_FILE_MAP in finding.py add soc2.json to FRAMEWORK_FILE_MAP in finding.py * feat: add soc2 to SUPPORTED_FRAMEWORKS in compliance.py Added 'soc2' to the list of supported compliance frameworks. * Add SOC 2 controls for data protection and management * Refactor/azure client network methods (#22) * refactor: add get_virtual_networks() and get_public_ip_addresses() to AzureClient * Refactor DDoS protection check to use azure_client * refactor: AZ-NET-006 now uses azure_client.get_public_ip_addresses() * feat: add CI pipeline with 6 automated checks (#34) - Python syntax check on all rule files - Rule structure validation (RULE_ID, SEVERITY, FRAMEWORKS) + RULE_ID uniqueness - Hardcoded credential scan - Playbook existence + bash syntax check for every rule - Compliance JSON validation for all four framework files (inc. soc2.json) - API syntax check - Compliance vs rule cross-reference check - CI summary step with per-check pass/fail table (if: always) - Fix duplicate DESCRIPTION assignment in az_net_003.py - Add pyyaml to requirements.txt for local YAML validation - Add docs/ci-pipeline.md with local run commands and design rationale - Update CI_PIPELINE_GUIDE.md with final PR description Closes #30 * docs: update .github/ISSUE_TEMPLATE/new_rule.md to reflect current codebase state * docs: update .github/PULL_REQUEST_TEMPLATE.md to reflect current codebase state * docs: update CONTRIBUTING.md to reflect current codebase state * docs: update README.md to reflect current codebase state * docs: update compliance/frameworks/iso27001.json to reflect current codebase state * docs: update compliance/frameworks/nist_csf.json to reflect current codebase state * docs: update docs/adding-a-rule.md to reflect current codebase state * docs: update docs/architecture.md to reflect current codebase state * docs: update docs/az-stor-003-test-plan.md to reflect current codebase state * docs: update docs/azure-setup.md to reflect current codebase state * docs: update docs/ci-pipeline.md to reflect current codebase state * docs: update docs/sentinel-setup.md to reflect current codebase state * docs: update sentinel/TEST_PLAN.md to reflect current codebase state * docs: update docs/api-reference.md to reflect current codebase state * docs: update docs/rules-reference.md to reflect current codebase state * docs: update README.md for professional open source style * docs: update CONTRIBUTING.md for professional open source style * docs: update docs/adding-a-rule.md for professional open source style * docs: update deployment guide to use Render instead of Azure App Service * feat: add rule AZ-STOR-004 storage account diagnostic logging check (#39) * feat: add rule AZ-STOR-004 storage account diagnostic logging check Detects Azure storage accounts where diagnostic logging is not fully enabled on blob, queue, or table services. Emits one finding per non-compliant service (StorageRead, StorageWrite, StorageDelete must all be enabled). Adds get_storage_service_logging() to AzureClient using MonitorManagementClient. Includes remediation playbook that enables all three services in one run. Frameworks: CIS 3.3, NIST DE.CM-7, ISO 27001 A.12.4.1 * chore: add AZ-STOR-004 compliance mappings --------- Co-authored-by: Shaurya K Sharma * feat: add rule AZ-IDN-003 Adds scanner rule AZ-IDN-003 detecting Entra ID (#48) * feat: add scanner rule AZ-IDN-003 — guest user invitations not restricted to admins * feat: add remediation playbook fix_az_idn_003.sh This script restricts guest user invitations to only admins and users with the Guest Inviter role in Azure Active Directory. * feat: add AZ-IDN-003 to CIS compliance framework Added control for guest invite restrictions to enhance security. * feat: add AZ-IDN-003 to NIST compliance framework * feat: add AZ-IDN-003 to ISO27001 compliance framework Added control AZ-IDN-003 for user registration and de-registration process. * feat: add AZ-IDN-003 to SOC2 compliance framework * feat: add rule AZ-CMP-002 — VM disk not protected by CMK or ADE (#47) * feat: add scanner rule AZ-CMP-002 — VM disk not protected by CMK or ADE This script detects virtual machines whose disks use platform-managed encryption only and provides findings for compliance with CIS 7.2. * feat: add remediation playbook fix_az_cmp_002.sh This script enables Azure Disk Encryption on a specified virtual machine using a Key Vault for the disk encryption key. * feat: add AZ-CMP-002 to CIS compliance framework Added a new control for OS disk encryption requirements. * feat: add AZ-CMP-002 to NIST compliance framework * feat: add AZ-CMP-002 to ISO27001 compliance framework Added control AZ-CMP-002 regarding cryptographic controls policy and its requirements. * feat: add AZ-CMP-002 to SOC2 compliance framework * fix: correct indentation in CIS AZ-CMP-002 entry * feat: add remediation playbook fix_az_cmp_002.sh to correct location This script enables Azure Disk Encryption on a specified virtual machine using a provided Key Vault for disk encryption. * Delete fix_az_cmp_002.sh * Feat/api deployment (#46) * feat: deploy API to Render with security hardening and CI/CD optimizations * feat: finalize Render deployment with security hardening and Gunicorn import fix * fix: GitHub Actions syntax and secret detection logic in deploy workflow * ix: harden scan trigger route with detailed error handling and remove redundant DB initialization * fix: implement global database connection management and harden all API routes * ix: prevent insecure smoke tests on main branch by enforcing JWT_SECRET presence and prevent CI false negatives in playbook check by enforcing non-empty glob match * fix: resolve Render startup crash and harden scan serialization against recursive objects * fix: add missing six and cryptography dependencies for Azure SDK compatibility * fix: increase CI wait time for Render build and add missing msrest dependencies * feat: integrate real subscription ID into smoke tests and CI/CD pipeline * feat: integrate real Azure_ ID's into smoke tests and CI/CD pipeline * feat: add root welcome route to confirm API status * fix: resolve specific CI credential flags in code and workflow while maintaining documentation standards * fix: resolve IndentationError in CI compliance cross-reference check * fix: resolve dependency issue and test on deployment * fix: resolve somke test TC-21 * fix: RUN_REAL_SCAN not set → TC-13/TC-14 skip → 21/21 pass for new live API url test * fix: scan.py deferred import from scanner.engine import ScanEngine was running before the subscription_id check * fix: restrict deploy triggers to dev and main, enable RUN_REAL_SCAN for maintainer CI, and update test plan documentation * feat: AZ-NET-011 Network Watcher not enabled in all regions (#42) * feat: add AZ-NET-011 Network Watcher rule, playbook and compliance mappings * fix: add missing AzureClient methods, SOC2 mapping and fix playbook region * fix: add SOC2 CC7.2 to FRAMEWORKS in az_net_011.py * feat: add AZ-DB-003 PostgreSQL Flexible Server SSL enforcement rule a… (#49) * feat: add AZ-DB-003 PostgreSQL Flexible Server SSL enforcement rule and playbook * fix: correct requirements.txt formatting for postgresqlflexibleserver * fix: correct postgresqlflexibleservers package name and version * fix: handle empty params gracefully and clean up playbook output * [RULE] AZ-CMP-003: VM without endpoint protection installed (#57) * feat: add scanner rule AZ-CMP-003 — VM without endpoint protection installed This script scans Azure VMs to check for the presence of recognized endpoint protection extensions. It logs findings for VMs without the required protection. * feat: add remediation playbook fix_az_cmp_003.sh This script installs endpoint protection on Azure VMs based on the operating system specified. It supports both Linux and Windows VMs. * feat: add AZ-CMP-003 to CIS compliance framework * feat: add AZ-CMP-003 to NIST compliance framework * feat: add AZ-CMP-003 to ISO27001 compliance framework * feat: add AZ-CMP-003 to SOC2 compliance framework * feat: add get_vm_extensions method to AzureClient Add method to retrieve VM extensions for a given VM. * fix: correct indentation and return type in get_vm_extensions * Add 1 more space in the code * add 4 space beofre def Add method to retrieve VM extensions for a given VM. * [DOCS] Add OpenShield learning and onboarding portal (#51) * docs: add OpenShield learning portal * Fix formatting for Learn OpenShield section --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> * refactor: reuse database connection per request using Flask g (#41) * fix: improve scan routes error handling and database reuse * fix: add database connection reuse and DATABASE_URL validation to score.py * fix: add database connection reuse, DATABASE_URL validation, and FileNotFoundError handling to compliance.py * fix: enforce JWT_SECRET environment variable, remove hardcoded default * ci: trigger fresh CI run * fix: all requirements - g.db naming, teardown, close() method * docs: add security policy, issue template, and README badges (#64) * feat: add rule AZ-KV-004 Key Vault purge protection disabled (#55) * feat: add rule AZ-KV-004 Key Vault purge protection disabled * fix: address PR review feedback for AZ-KV-004 - Add SOC2 CC9.1 mapping to FRAMEWORKS dict - Add AZ-KV-004 entries to all four compliance framework JSON files - Add set -euo pipefail to playbook - Add resource_group to metadata dict * feat: add AZ-STOR-005 geo-redundant storage rule (#74) - scanner/rules/az_stor_005.py: detects storage accounts using LRS or ZRS (non-geo-redundant) replication; flags them as MEDIUM severity - playbooks/cli/fix_az_stor_005.sh: CLI remediation to update storage account SKU to a geo-redundant option (Standard_GRS by default); validates target SKU against allowed geo-redundant values - compliance/frameworks/*.json: adds AZ-STOR-005 entry to CIS Azure Benchmark (3.1), NIST CSF (PR.IP-4), ISO 27001 (A.17.2.1), and SOC 2 (A1.2) Closes #71 Co-authored-by: Shaurya K Sharma * feat: add rule AZ-DB-004 SQL Server firewall allows all Azure services (#70) * feat: add rule AZ-DB-004 SQL Server firewall allows all Azure services - Add scanner rule az_db_004.py detecting SQL Servers with Allow Azure services firewall rule enabled - Add remediation playbook fix_az_db_004.sh - Add get_sql_server_firewall_rules method to AzureClient - Add AZ-DB-004 entries to all four compliance framework JSON files * fix: add get_sql_server_firewall_rules to AzureClient * fix: remove duplicate import, fix indentation, add return None to auditing policy * docs: add 6 README badges (#79) * feat: add AZ-KV-005 Key Vault certificate expiring within 30 days (#75) * Remove duplicate import of MonitorManagementClient * Add method to get Key Vault certificates Added a new method to list certificates in a Key Vault. * Add AZ-KV-005 rule for expiring Key Vault certificates This script scans Azure Key Vaults for certificates that are expiring within 30 days and do not have auto-renewal enabled. It logs findings and provides remediation steps. * Add script to enable auto-renewal for Key Vault certificate This script enables auto-renewal for an expiring Key Vault certificate by updating its policy. * Add controls for Azure Key Vault security measures * Add AZ-KV-005 control for certificate maintenance * Add controls for key management and availability * Add SOC 2 controls for Azure Key Vault risk mitigation * Fix indentation in get_key_vaults method * Add azure-keyvault-certificates dependency * Enhance script error handling with pipefail option * Refactor lifetime_actions assignment for clarity * Add control for expiring certificate maintenance Added a new control for certificate maintenance in Azure Key Vault. * fix: add missing comma in soc2.json after AZ-KV-005 entry * fix: add missing comma in iso27001.json after AZ-KV-005 entry * [RULE] AZ-CMP-004: VM without automatic OS patching enabled (#73) * Added az_cmp_004.py to check VM patching status This script checks Azure VMs for automatic OS patching status and collects findings for those without it enabled. * Added script to enable automatic OS patching for VMs This script enables automatic OS patching for both Windows and Linux VMs in Azure. It requires a resource group and VM name as input, defaulting to Windows if the OS type is not specified. * Add control for OS patching requirement in CIS benchmark * Add vulnerability management control to NIST CSF * Added control AZ-CMP-004 for vulnerability management * Added SOC 2 controls for endpoint protection and OS patching * Fix JSON formatting in cis_azure_benchmark.json * Fix JSON formatting in nist_csf.json * Improve error handling in fix_az_cmp_004.sh Updated script to use 'set -euo pipefail' for better error handling. * Update patching condition for Windows configuration Refine condition for patching approval based on patch mode. * Fix indentation and formatting in az_cmp_004.py * feat: add AI provider abstraction layer for Anthropic, Groq and Gemini (#89) * feat: initialise api/services package * feat: add AI provider abstraction layer for Anthropic, Groq and Gemini * fix: add module docstring to ai_provider.py Added a docstring explaining the purpose of the AI provider abstraction layer. * fix: make model configurable with sensible defaults per provider * Smoke Test Alginment after the recent changes to the Repository causing the Deployment CI failure (#88) * fix: test align smoke tests with API behavior and environment * test: deploy.yml run after smoke test alginment * fix: smoke test aligned after recent codebase changes * feat: add AZ-IDN-004 PIM not configured for admin roles rule and play… (#77) * feat: add AZ-IDN-004 PIM not configured for admin roles rule and playbook * fix: fetch Graph API token once and reuse headers for both API calls * fix: correct malformed JSON in cis_azure_benchmark.json for AZ-IDN-004 entry --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> * feat: add AI executive summary and remediation endpoint (#95) * feat: add AI insights endpoint * ci: scan only quoted-literal credential assignments --------- Co-authored-by: Shaurya K Sharma * feat(scanner): add AZ-NET-014 VNet peering gateway transit rule (#94) - Add scanner/rules/az_net_014.py to detect VNet peerings with allowGatewayTransit or useRemoteGateways enabled - Add get_vnet_peerings() and get_azure_firewalls() to azure_client.py - Add playbooks/cli/fix_az_net_014.sh remediation script - Update all 4 compliance framework JSONs with AZ-NET-014 mappings * feat: add AZ-NET-013 Azure Firewall VNet rule (#99) Co-authored-by: Shaurya K Sharma * Implement AI Q&A over scan findings (#98) Co-authored-by: Shaurya K Sharma * Feat/CVE correlation (#96) * fix: smoke test aligned after recent codebase changes * feat: add CVE correlation via MITRE NVD API * fix: ensure the run migration logic handles edge cases * fix: sync with dev after merged PRs, fix compliance duplication, indentaion and omttion of AZ-STOR-04 * fix: CVE prefix mappings, use legacy-only enrichment, clean up tests, and align CVE correlation docs. * fix: findings DB cleanup, AI title fallback, and persist CVE enrichment * feat: add RAG powered AI insights layer with Azure security skill embeddings (#97) * Create __init__.py * Implement OpenShield vector store builder This script builds the OpenShield knowledge base vector store for RAG AI insights by collecting rules and compliance documents, then embedding them into a vector store. * Add AI insights routes for summary, prioritisation, and Q&A * Implement knowledge retrieval from vector store This module retrieves relevant knowledge from the OpenShield vector store for retrieval-augmented generation (RAG). It includes error handling for missing vector stores and the chromadb dependency. * Register AI blueprint in the Flask app * Add chromadb version 0.4.24 to requirements * feat: add Azure security skills into knowledge base for RAG embedding * feat: wire Azure skill documents into embedding pipeline * Add sentence-transformers version 2.7.0 to requirements * ignore generated ai vectorstore directory * Refactor AI insights routes for clarity and updates * fix: deduplicate ai_bp and restore missing score_bp import in app.py * Refactor severity handling and update prompts * merge dev into feat/rag-ai-insights, resolve ai.py conflict * trigger CI * Remove AZ-CMP-003 and update AZ-NET-014 description Removed control AZ-CMP-003 related to unauthorized software detection and updated control AZ-NET-014 description for clarity. * feat: add AZ-NET-012 - NSG flow logs not enabled rule (#76) * ci: trigger fresh CI run * Dev (#50) * chore: add skeleton files and requirements * fix: remove embedded git repo * Core Structure Created * feat: build complete core — scanner engine, 10 rules, API, playbooks, compliance mappings, docs * docs: replace ASCII architecture with interactive Mermaid diagram * feat: Sentinel integration — ingest.py, 4 KQL rules, setup guide (#12) * feat: add sentinel/ingest.py — Log Analytics ingestion via HMAC-SHA256 * feat: add sentinel/__init__.py * feat: add KQL rule — HIGH severity finding detected * feat: add KQL rule — misconfiguration wave detection * feat: add KQL rule — new resource type critical detection * Delete sentinel/rules directory * Create rules * Delete sentinel/rules * Add KQL rule for high severity findings * Add Misconfiguration Wave detection rule * Add KQL rule for persistent misconfiguration detection * Add KQL rule for new critical resource types This rule identifies new resource types with critical findings that have occurred in the last 24 hours, excluding known types from the last 30 days. * Add script to generate test findings in JSON format This script generates test findings related to security compliance and saves them in a JSON file. * Add Sentinel integration test plan and results Added a comprehensive test plan for Sentinel integration, detailing test objectives, results, and acceptance criteria for various KQL rules and data ingestion. * docs: add sentinel integration setup guide Added a comprehensive setup guide for integrating Sentinel with Azure, covering prerequisites, workspace creation, activation, environment variable setup, ingestion, log verification, KQL rules deployment, and incident verification. * fix: add AZ-STOR-003 compliance mappings, correct NIST control to PR.DS-3 * docs: add real-world breach scenarios for all 10 starter rules (#15) * feat: add AZ-KV-002 key vault public access rule and remediation playbook (#14) * docs: update README with rule count, roadmap progress and contributors * feat: add network security rules AZ-NET-003 to AZ-NET-010 (#16) * Add az_net_003.py to check NSG rules for port 443 This script detects Network Security Groups (NSGs) with unrestricted inbound access on port 443 and provides remediation guidance. * Add AZ-NET-004 rule for empty NSG detection This script detects Network Security Groups (NSGs) that have no custom security rules configured, providing details for remediation. * Add AZ-NET-005 rule for DDoS protection check This script detects virtual networks in Azure that do not have DDoS protection enabled and provides remediation steps. * feat: add rule AZ-NET-006 — public IP unassociated with any resource This rule detects public IP addresses that are not associated with any resource, providing details for remediation. * feat: add rule AZ-NET-007 — Application Gateway without WAF enabled This rule detects Application Gateways that do not have WAF enabled, logging findings and providing remediation steps. * feat: add rule AZ-NET-008 — load balancer with no backend pool This rule detects load balancers in Azure that are not configured with a backend pool, indicating potential misconfiguration or unnecessary costs. * feat: add rule AZ-NET-009 — VPN gateway using outdated IKE version This script detects VPN gateways using the outdated IKEv1 protocol and provides remediation steps to migrate to IKEv2. * feat: add rule AZ-NET-010 — subnet with no NSG attached This script detects subnets in Azure that do not have a Network Security Group (NSG) attached, logging findings and providing remediation guidance. * feat: add playbook fix_az_net_003.sh This script updates the NSG rule to restrict inbound traffic on port 443 to a specified IP range. * feat: add playbook fix_az_net_004.sh This script adds a default deny-all inbound rule to a specified NSG. * feat: add playbook fix_az_net_005.sh This script enables DDoS protection on a specified virtual network in Azure. It checks for required parameters and provides usage instructions if they are missing. * feat: add playbook fix_az_net_006.sh This script deletes unassociated public IP addresses in Azure. * feat: add playbook fix_az_net_007.sh This script enables WAF on an Application Gateway, ensuring compliance with the AZ-NET-007 rule. * feat: add playbook fix_az_net_008.sh Script to remediate AZ-NET-008 by deleting empty load balancers. * feat:add script to update VPN connection to IKEv2 This script updates a VPN connection to use IKEv2, ensuring compliance with the AZ-NET-009 rule. * feat: add playbook fix_az_net_010.sh This script attaches a specified network security group to a given subnet in a virtual network, ensuring compliance with the AZ-NET-010 rule. * Clarify description and add note for public-facing services Updated the description to clarify the risk of exposing port 443 and added a note regarding public-facing services. * Change severity level from MEDIUM to HIGH * fix: AZ-NET-005 severity changed to LOW — DDoS Standard high cost on small subscriptions * Add note about NetworkManagementClient usage Added a note regarding the creation of NetworkManagementClient directly and suggested a follow-up for consistency. * Add note about NetworkManagementClient usage Added a note regarding the use of NetworkManagementClient and suggested a follow-up for consistency. * Add additional security controls to CIS Azure benchmark * Refine control descriptions in nist_csf.json Updated descriptions for various controls to enhance clarity and specificity regarding remote access management, data protection, and security measures. * fix: add AZ-NET-003 to AZ-NET-010 to ISO27001 compliance framework Updated descriptions for various controls to clarify compliance requirements and improve security guidance. --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> * Feat/az stor 003 (#21) * feat: add rule AZ-STOR-003 storage lifecycle policy check * feat: add rule AZ-STOR-003 storage lifecycle policy check * docs: add SOC 2 Type II compliance framework mapping (#33) * docs: add SOC 2 Type II compliance framework mapping for all 20 rules Added SOC 2 Type II framework with detailed controls for security measures and compliance requirements. * feat: add soc2 to FRAMEWORK_FILE_MAP in finding.py add soc2.json to FRAMEWORK_FILE_MAP in finding.py * feat: add soc2 to SUPPORTED_FRAMEWORKS in compliance.py Added 'soc2' to the list of supported compliance frameworks. * Add SOC 2 controls for data protection and management * Refactor/azure client network methods (#22) * refactor: add get_virtual_networks() and get_public_ip_addresses() to AzureClient * Refactor DDoS protection check to use azure_client * refactor: AZ-NET-006 now uses azure_client.get_public_ip_addresses() * feat: add CI pipeline with 6 automated checks (#34) - Python syntax check on all rule files - Rule structure validation (RULE_ID, SEVERITY, FRAMEWORKS) + RULE_ID uniqueness - Hardcoded credential scan - Playbook existence + bash syntax check for every rule - Compliance JSON validation for all four framework files (inc. soc2.json) - API syntax check - Compliance vs rule cross-reference check - CI summary step with per-check pass/fail table (if: always) - Fix duplicate DESCRIPTION assignment in az_net_003.py - Add pyyaml to requirements.txt for local YAML validation - Add docs/ci-pipeline.md with local run commands and design rationale - Update CI_PIPELINE_GUIDE.md with final PR description Closes #30 * docs: update .github/ISSUE_TEMPLATE/new_rule.md to reflect current codebase state * docs: update .github/PULL_REQUEST_TEMPLATE.md to reflect current codebase state * docs: update CONTRIBUTING.md to reflect current codebase state * docs: update README.md to reflect current codebase state * docs: update compliance/frameworks/iso27001.json to reflect current codebase state * docs: update compliance/frameworks/nist_csf.json to reflect current codebase state * docs: update docs/adding-a-rule.md to reflect current codebase state * docs: update docs/architecture.md to reflect current codebase state * docs: update docs/az-stor-003-test-plan.md to reflect current codebase state * docs: update docs/azure-setup.md to reflect current codebase state * docs: update docs/ci-pipeline.md to reflect current codebase state * docs: update docs/sentinel-setup.md to reflect current codebase state * docs: update sentinel/TEST_PLAN.md to reflect current codebase state * docs: update docs/api-reference.md to reflect current codebase state * docs: update docs/rules-reference.md to reflect current codebase state * docs: update README.md for professional open source style * docs: update CONTRIBUTING.md for professional open source style * docs: update docs/adding-a-rule.md for professional open source style * docs: update deployment guide to use Render instead of Azure App Service * feat: add rule AZ-STOR-004 storage account diagnostic logging check (#39) * feat: add rule AZ-STOR-004 storage account diagnostic logging check Detects Azure storage accounts where diagnostic logging is not fully enabled on blob, queue, or table services. Emits one finding per non-compliant service (StorageRead, StorageWrite, StorageDelete must all be enabled). Adds get_storage_service_logging() to AzureClient using MonitorManagementClient. Includes remediation playbook that enables all three services in one run. Frameworks: CIS 3.3, NIST DE.CM-7, ISO 27001 A.12.4.1 * chore: add AZ-STOR-004 compliance mappings --------- Co-authored-by: Shaurya K Sharma * feat: add rule AZ-IDN-003 Adds scanner rule AZ-IDN-003 detecting Entra ID (#48) * feat: add scanner rule AZ-IDN-003 — guest user invitations not restricted to admins * feat: add remediation playbook fix_az_idn_003.sh This script restricts guest user invitations to only admins and users with the Guest Inviter role in Azure Active Directory. * feat: add AZ-IDN-003 to CIS compliance framework Added control for guest invite restrictions to enhance security. * feat: add AZ-IDN-003 to NIST compliance framework * feat: add AZ-IDN-003 to ISO27001 compliance framework Added control AZ-IDN-003 for user registration and de-registration process. * feat: add AZ-IDN-003 to SOC2 compliance framework * feat: add rule AZ-CMP-002 — VM disk not protected by CMK or ADE (#47) * feat: add scanner rule AZ-CMP-002 — VM disk not protected by CMK or ADE This script detects virtual machines whose disks use platform-managed encryption only and provides findings for compliance with CIS 7.2. * feat: add remediation playbook fix_az_cmp_002.sh This script enables Azure Disk Encryption on a specified virtual machine using a Key Vault for the disk encryption key. * feat: add AZ-CMP-002 to CIS compliance framework Added a new control for OS disk encryption requirements. * feat: add AZ-CMP-002 to NIST compliance framework * feat: add AZ-CMP-002 to ISO27001 compliance framework Added control AZ-CMP-002 regarding cryptographic controls policy and its requirements. * feat: add AZ-CMP-002 to SOC2 compliance framework * fix: correct indentation in CIS AZ-CMP-002 entry * feat: add remediation playbook fix_az_cmp_002.sh to correct location This script enables Azure Disk Encryption on a specified virtual machine using a provided Key Vault for disk encryption. * Delete fix_az_cmp_002.sh * Feat/api deployment (#46) * feat: deploy API to Render with security hardening and CI/CD optimizations * feat: finalize Render deployment with security hardening and Gunicorn import fix * fix: GitHub Actions syntax and secret detection logic in deploy workflow * ix: harden scan trigger route with detailed error handling and remove redundant DB initialization * fix: implement global database connection management and harden all API routes * ix: prevent insecure smoke tests on main branch by enforcing JWT_SECRET presence and prevent CI false negatives in playbook check by enforcing non-empty glob match * fix: resolve Render startup crash and harden scan serialization against recursive objects * fix: add missing six and cryptography dependencies for Azure SDK compatibility * fix: increase CI wait time for Render build and add missing msrest dependencies * feat: integrate real subscription ID into smoke tests and CI/CD pipeline * feat: integrate real Azure_ ID's into smoke tests and CI/CD pipeline * feat: add root welcome route to confirm API status * fix: resolve specific CI credential flags in code and workflow while maintaining documentation standards * fix: resolve IndentationError in CI compliance cross-reference check * fix: resolve dependency issue and test on deployment * fix: resolve somke test TC-21 * fix: RUN_REAL_SCAN not set → TC-13/TC-14 skip → 21/21 pass for new live API url test * fix: scan.py deferred import from scanner.engine import ScanEngine was running before the subscription_id check * fix: restrict deploy triggers to dev and main, enable RUN_REAL_SCAN for maintainer CI, and update test plan documentation * feat: AZ-NET-011 Network Watcher not enabled in all regions (#42) * feat: add AZ-NET-011 Network Watcher rule, playbook and compliance mappings * fix: add missing AzureClient methods, SOC2 mapping and fix playbook region * fix: add SOC2 CC7.2 to FRAMEWORKS in az_net_011.py * feat: add AZ-DB-003 PostgreSQL Flexible Server SSL enforcement rule a… (#49) * feat: add AZ-DB-003 PostgreSQL Flexible Server SSL enforcement rule and playbook * fix: correct requirements.txt formatting for postgresqlflexibleserver * fix: correct postgresqlflexibleservers package name and version * fix: handle empty params gracefully and clean up playbook output --------- Co-authored-by: Tanvir Farhad Co-authored-by: PARTH J ROHIT Co-authored-by: Ritik Sah Co-authored-by: Shaurya K Sharma Co-authored-by: Shaurya K Sharma Co-authored-by: Mahfuzur Rahman Emon * refactor: reuse database connection per request using Flask g (#41) * fix: improve scan routes error handling and database reuse * fix: add database connection reuse and DATABASE_URL validation to score.py * fix: add database connection reuse, DATABASE_URL validation, and FileNotFoundError handling to compliance.py * fix: enforce JWT_SECRET environment variable, remove hardcoded default * ci: trigger fresh CI run * fix: all requirements - g.db naming, teardown, close() method * fix: update az_net_012.py to match az_cmp_003 pattern and add set -euo pipefail to bash script * fix: correct az_net_012.py signature, add set -euo pipefail, add AZ-NET-012 to all compliance files * fix: correct az_net_012.py to match az_cmp_003 pattern --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> Co-authored-by: Tanvir Farhad Co-authored-by: PARTH J ROHIT Co-authored-by: Ritik Sah Co-authored-by: Shaurya K Sharma Co-authored-by: Shaurya K Sharma Co-authored-by: Mahfuzur Rahman Emon * fix: resolve CodeQL warnings in embed.py and test files * feat(frontend): build complete 7-page security dashboard (#111) * Basic components and pages with dummy data * feat(frontend): build complete 7-page security dashboard Complete React 18 + Vite frontend for OpenShield security platform. Pages (7): - Monitoring — security score gauge, trend chart, findings distribution, issues by resource group, category scores - Discovery — resource table with issue counts, risk filters, category grouping, resource group filtering, clickable category cards - Prioritization — risk vs effort matrix, ranked list with quick remediation preview, all 25 action items; click-to-select syncs matrix + action items + remediation panel - Detailed Scan — findings list with playbook tabs (portal/CLI/validation), navigates from Prioritization with context banner - Compliance — CIS/NIST/ISO27001/SOC2 framework cards, controls table, comparison trend chart, CSV/JSON export - Drift — configuration change timeline, ADDED/REMOVED/MODIFIED events with before/after values, who changed it and when - AI Assistant — 3-column layout (findings picker, chat, suggestions + CVE analysis + executive summary); AI chat wired to aiApi.js with smart mock responses; finding context passed from Scan page API service layer (src/utils/api.js): - Demo/Live mode toggle persisted in localStorage - JWT token bootstrap in App.jsx - Health check on startup with auto-fallback to demo mode - Real fetch calls with mock fallback for every endpoint: /api/score, /api/findings, /api/findings/:id, /api/findings/:id/playbook, /api/resources, /api/prioritization, /api/drift, /api/scans, /api/scans/trigger, /api/scans/:id, /api/compliance/cis|nist|iso27001 - snake_case → camelCase normalisation for all backend responses - Separate aiApi.js for AI endpoints with smart mock responses Header features: - Run Scan button with live polling (4s interval, 5-min timeout, elapsed timer) - Demo/Live badge with connection test before switching - Error popup if backend is unreachable Design system: - Tailwind CSS v3 with custom tokens (brand, severity, bg-dark, status) - Dark mode via class strategy, persisted in localStorage - Fully responsive — mobile hamburger drawer, stacked layouts on sm - Dot-pattern background, soft shadows, consistent 4px grid Mock data: - 8 api.*.json files matching exact backend response schema - API_ENDPOINTS.txt — backend contract document with implementation status, database schema, seed data, and endpoint ordering guide Co-Authored-By: Claude Sonnet 4.6 * feat(frontend): wire live backend, fix JWT auth, add Vercel deployment config - Fix JWT: read VITE_JWT_TOKEN env var so live API calls authenticate correctly (was sending plain string 'dev-demo-token' which backend rejected as invalid JWT) - Add vercel.json with SPA rewrites so /monitoring, /scan etc don't 404 - Monitoring page now fetches real score + findings in live mode and computes stats/distribution/resource-group breakdown from actual backend data - Run Scan button shows subscription ID input in live mode (optional — backend falls back to AZURE_SUBSCRIPTION_ID env var if blank) - api.js: no silent localhost fallback in production builds (fails loudly if VITE_API_URL is not set) --------- Co-authored-by: Claude Sonnet 4.6 * Feat/jwt secret prod fail closed (#117) * fix: smoke test aligned after recent codebase changes * feat: fail closed on insecure JWT_SECRET in production * fix: rename _DEFAULT_JWT_SECRET to avoid CI credential scanner false positive * feat: AI-004 RAG Pipeline - Document Ingestion and Vector Store (#104) * feat: add AZ-IDN-004 PIM not configured for admin roles rule and playbook * feat: add RAG pipeline with document loader, chunker, embedder, ChromaDB vector store and Flask API routes * fix: remove duplicate ai files, restore deleted compliance rules, revert requirements to chromadb 0.4.24 * fix: update gitignore to use ai/vectorstore/ and clean up README references * fix: add missing newline at EOF in compliance JSON files * Potential fix for pull request finding 'Unused import' Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> * feat: add PQC compliance mappings, azure client methods and dependencies * docs: update README with post-quantum cryptography scanning and rule count * Feat/live data wiring (#122) * fix: smoke test aligned after recent codebase changes * feat: wire live backend, implement missing endpoints, fix deploy crash - api.js/aiApi.js: default to live mode, hardcode Render URL fallback, non-persisted cold-start fallback, fix isDemoOrUnconfigured check - App.jsx: retry health probe 5x15s for Render cold start - AILayer.jsx: add catch to Promise.all so summary spinner always clears - scanner/engine.py: add status completed to scan result - api/routes/resources.py: new GET /api/resources from findings - api/routes/prioritization.py: new GET /api/prioritization ranked by score - api/routes/drift.py: new GET /api/drift from scan comparison - api/routes/findings.py: new GET /api/findings/:id/playbook from cli scripts - api/app.py: remove duplicate module-level ai_bp import that crashed gunicorn - requirements.txt: pin numpy<2.0 to fix chromadb startup crash on Render - deploy.yml: add feat/live-data-wiring to push triggers * fix: make all GET /api/* endpoints public for demo dashboard removes JWT requirement from read-only routes so the Vercel frontend works without VITE_JWT_TOKEN; POST endpoints remain protected * fix: update smoke tests for public GET auth model, accept scan timeout - TC-18/19: switched from GET /api/findings (now public) to POST /api/scans/trigger which still requires JWT — better security coverage - TC-21: added status 0 as acceptable outcome; when AZURE_SUBSCRIPTION_ID is set on Render the server starts a real scan and the 45s client timeout fires before it completes — that is not a crash - app.py: all GET /api/* public, POST endpoints remain JWT-protected * feat: image/video support, drag-drop upload, Vercel-ready config, full README - assets/blog/.gitkeep: track empty directory for blog images - vercel.json: CSP allows Tailwind/Lucide CDNs and YouTube/Vimeo iframes; X-Frame-Options changed to SAMEORIGIN; Permissions-Policy added - script.js: real drag-and-drop on image upload zone with visual feedback - script.js: image size limit fixed from 2MB to 700KB with clear error (GitHub Contents API rejects base64 payloads over 1MB) - script.js: toEmbedUrl() converts YouTube watch URLs and Vimeo URLs to embed URLs automatically - script.js: blog posts render video embed above content if video field set - script.js: editor preview shows video iframe in real time - script.js: blog editor saves video embed URL to content entry - index.html: Video Embed URL field added to blog editor (YouTube/Vimeo) - index.html: image upload zone has id for drag-drop wiring - README.md: full maintainer guide — deployment, all content types, image/video guidelines, rules gallery update process, editor coverage table * fix: apply CORS to all routes not just /api/* so /health is accessible from Vercel * fix: scope score/findings/cve-summary to latest scan, make last-scanned dynamic - finding.py get_score(): was counting ALL findings across ALL scans — 3 seeded scans with ~37 findings total drove score to 0; now scoped to latest scan_id only - finding.py get_cve_summary(): same fix — latest scan scope - finding.py get_findings(): when no scan_id filter given, default to latest scan so dashboard shows current posture not historical accumulation - Header.jsx: replace hardcoded 'May 29, 2026 6:00 PM' with dynamic fetch from api.getScans() on mount, formatted in user local timezone * feat: implement resources, prioritization, drift, playbook endpoints; remove frontend mock data * fix: always prefer VITE_JWT_TOKEN over stale localStorage value * fix: compliance trend from scan history, fix AI tab crash * merge: resolve final README conflict in roadmap checklist * feat: add PQC to discovery icon map and website rules gallery * Feat/decouple CVE enrichment (#127) * fix: smoke test aligned after recent codebase changes * feat: decouple CVE enrichment into dedicated on-demand endpoint * feat: decouple CVE enrichment into dedicated on-demand endpoint adressed feedback * docs: update OpenShield Learn content, navigation, and hosting support (#126) * feat: add AZ-PQC-001 to AZ-PQC-003 post-quantum cryptography scanner rules (#121) * chore: add skeleton files and requirements * fix: remove embedded git repo * Core Structure Created * feat: build complete core — scanner engine, 10 rules, API, playbooks, compliance mappings, docs * docs: replace ASCII architecture with interactive Mermaid diagram * feat: Sentinel integration — ingest.py, 4 KQL rules, setup guide (#12) * feat: add sentinel/ingest.py — Log Analytics ingestion via HMAC-SHA256 * feat: add sentinel/__init__.py * feat: add KQL rule — HIGH severity finding detected * feat: add KQL rule — misconfiguration wave detection * feat: add KQL rule — new resource type critical detection * Delete sentinel/rules directory * Create rules * Delete sentinel/rules * Add KQL rule for high severity findings * Add Misconfiguration Wave detection rule * Add KQL rule for persistent misconfiguration detection * Add KQL rule for new critical resource types This rule identifies new resource types with critical findings that have occurred in the last 24 hours, excluding known types from the last 30 days. * Add script to generate test findings in JSON format This script generates test findings related to security compliance and saves them in a JSON file. * Add Sentinel integration test plan and results Added a comprehensive test plan for Sentinel integration, detailing test objectives, results, and acceptance criteria for various KQL rules and data ingestion. * docs: add sentinel integration setup guide Added a comprehensive setup guide for integrating Sentinel with Azure, covering prerequisites, workspace creation, activation, environment variable setup, ingestion, log verification, KQL rules deployment, and incident verification. * fix: add AZ-STOR-003 compliance mappings, correct NIST control to PR.DS-3 * docs: add real-world breach scenarios for all 10 starter rules (#15) * feat: add AZ-KV-002 key vault public access rule and remediation playbook (#14) * docs: update README with rule count, roadmap progress and contributors * feat: add network security rules AZ-NET-003 to AZ-NET-010 (#16) * Add az_net_003.py to check NSG rules for port 443 This script detects Network Security Groups (NSGs) with unrestricted inbound access on port 443 and provides remediation guidance. * Add AZ-NET-004 rule for empty NSG detection This script detects Network Security Groups (NSGs) that have no custom security rules configured, providing details for remediation. * Add AZ-NET-005 rule for DDoS protection check This script detects virtual networks in Azure that do not have DDoS protection enabled and provides remediation steps. * feat: add rule AZ-NET-006 — public IP unassociated with any resource This rule detects public IP addresses that are not associated with any resource, providing details for remediation. * feat: add rule AZ-NET-007 — Application Gateway without WAF enabled This rule detects Application Gateways that do not have WAF enabled, logging findings and providing remediation steps. * feat: add rule AZ-NET-008 — load balancer with no backend pool This rule detects load balancers in Azure that are not configured with a backend pool, indicating potential misconfiguration or unnecessary costs. * feat: add rule AZ-NET-009 — VPN gateway using outdated IKE version This script detects VPN gateways using the outdated IKEv1 protocol and provides remediation steps to migrate to IKEv2. * feat: add rule AZ-NET-010 — subnet with no NSG attached This script detects subnets in Azure that do not have a Network Security Group (NSG) attached, logging findings and providing remediation guidance. * feat: add playbook fix_az_net_003.sh This script updates the NSG rule to restrict inbound traffic on port 443 to a specified IP range. * feat: add playbook fix_az_net_004.sh This script adds a default deny-all inbound rule to a specified NSG. * feat: add playbook fix_az_net_005.sh This script enables DDoS protection on a specified virtual network in Azure. It checks for required parameters and provides usage instructions if they are missing. * feat: add playbook fix_az_net_006.sh This script deletes unassociated public IP addresses in Azure. * feat: add playbook fix_az_net_007.sh This script enables WAF on an Application Gateway, ensuring compliance with the AZ-NET-007 rule. * feat: add playbook fix_az_net_008.sh Script to remediate AZ-NET-008 by deleting empty load balancers. * feat:add script to update VPN connection to IKEv2 This script updates a VPN connection to use IKEv2, ensuring compliance with the AZ-NET-009 rule. * feat: add playbook fix_az_net_010.sh This script attaches a specified network security group to a given subnet in a virtual network, ensuring compliance with the AZ-NET-010 rule. * Clarify description and add note for public-facing services Updated the description to clarify the risk of exposing port 443 and added a note regarding public-facing services. * Change severity level from MEDIUM to HIGH * fix: AZ-NET-005 severity changed to LOW — DDoS Standard high cost on small subscriptions * Add note about NetworkManagementClient usage Added a note regarding the creation of NetworkManagementClient directly and suggested a follow-up for consistency. * Add note about NetworkManagementClient usage Added a note regarding the use of NetworkManagementClient and suggested a follow-up for consistency. * Add additional security controls to CIS Azure benchmark * Refine control descriptions in nist_csf.json Updated descriptions for various controls to enhance clarity and specificity regarding remote access management, data protection, and security measures. * fix: add AZ-NET-003 to AZ-NET-010 to ISO27001 compliance framework Updated descriptions for various controls to clarify compliance requirements and improve security guidance. --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> * Feat/az stor 003 (#21) * feat: add rule AZ-STOR-003 storage lifecycle policy check * feat: add rule AZ-STOR-003 storage lifecycle policy check * docs: add SOC 2 Type II compliance framework mapping (#33) * docs: add SOC 2 Type II compliance framework mapping for all 20 rules Added SOC 2 Type II framework with detailed controls for security measures and compliance requirements. * feat: add soc2 to FRAMEWORK_FILE_MAP in finding.py add soc2.json to FRAMEWORK_FILE_MAP in finding.py * feat: add soc2 to SUPPORTED_FRAMEWORKS in compliance.py Added 'soc2' to the list of supported compliance frameworks. * Add SOC 2 controls for data protection and management * Refactor/azure client network methods (#22) * refactor: add get_virtual_networks() and get_public_ip_addresses() to AzureClient * Refactor DDoS protection check to use azure_client * refactor: AZ-NET-006 now uses azure_client.get_public_ip_addresses() * feat: add CI pipeline with 6 automated checks (#34) - Python syntax check on all rule files - Rule structure validation (RULE_ID, SEVERITY, FRAMEWORKS) + RULE_ID uniqueness - Hardcoded credential scan - Playbook existence + bash syntax check for every rule - Compliance JSON validation for all four framework files (inc. soc2.json) - API syntax check - Compliance vs rule cross-reference check - CI summary step with per-check pass/fail table (if: always) - Fix duplicate DESCRIPTION assignment in az_net_003.py - Add pyyaml to requirements.txt for local YAML validation - Add docs/ci-pipeline.md with local run commands and design rationale - Update CI_PIPELINE_GUIDE.md with final PR description Closes #30 * docs: update .github/ISSUE_TEMPLATE/new_rule.md to reflect current codebase state * docs: update .github/PULL_REQUEST_TEMPLATE.md to reflect current codebase state * docs: update CONTRIBUTING.md to reflect current codebase state * docs: update README.md to reflect current codebase state * docs: update compliance/frameworks/iso27001.json to reflect current codebase state * docs: update compliance/frameworks/nist_csf.json to reflect current codebase state * docs: update docs/adding-a-rule.md to reflect current codebase state * docs: update docs/architecture.md to reflect current codebase state * docs: update docs/az-stor-003-test-plan.md to reflect current codebase state * docs: update docs/azure-setup.md to reflect current codebase state * docs: update docs/ci-pipeline.md to reflect current codebase state * docs: update docs/sentinel-setup.md to reflect current codebase state * docs: update sentinel/TEST_PLAN.md to reflect current codebase state * docs: update docs/api-reference.md to reflect current codebase state * docs: update docs/rules-reference.md to reflect current codebase state * docs: update README.md for professional open source style * docs: update CONTRIBUTING.md for professional open source style * docs: update docs/adding-a-rule.md for professional open source style * docs: update deployment guide to use Render instead of Azure App Service * feat: add rule AZ-STOR-004 storage account diagnostic logging check (#39) * feat: add rule AZ-STOR-004 storage account diagnostic logging check Detects Azure storage accounts where diagnostic logging is not fully enabled on blob, queue, or table services. Emits one finding per non-compliant service (StorageRead, StorageWrite, StorageDelete must all be enabled). Adds get_storage_service_logging() to AzureClient using MonitorManagementClient. Includes remediation playbook that enables all three services in one run. Frameworks: CIS 3.3, NIST DE.CM-7, ISO 27001 A.12.4.1 * chore: add AZ-STOR-004 compliance mappings --------- Co-authored-by: Shaurya K Sharma * feat: add rule AZ-IDN-003 Adds scanner rule AZ-IDN-003 detecting Entra ID (#48) * feat: add scanner rule AZ-IDN-003 — guest user invitations not restricted to admins * feat: add remediation playbook fix_az_idn_003.sh This script restricts guest user invitations to only admins and users with the Guest Inviter role in Azure Active Directory. * feat: add AZ-IDN-003 to CIS compliance framework Added control for guest invite restrictions to enhance security. * feat: add AZ-IDN-003 to NIST compliance framework * feat: add AZ-IDN-003 to ISO27001 compliance framework Added control AZ-IDN-003 for user registration and de-registration process. * feat: add AZ-IDN-003 to SOC2 compliance framework * feat: add rule AZ-CMP-002 — VM disk not protected by CMK or ADE (#47) * feat: add scanner rule AZ-CMP-002 — VM disk not protected by CMK or ADE This script detects virtual machines whose disks use platform-managed encryption only and provides findings for compliance with CIS 7.2. * feat: add remediation playbook fix_az_cmp_002.sh This script enables Azure Disk Encryption on a specified virtual machine using a Key Vault for the disk encryption key. * feat: add AZ-CMP-002 to CIS compliance framework Added a new control for OS disk encryption requirements. * feat: add AZ-CMP-002 to NIST compliance framework * feat: add AZ-CMP-002 to ISO27001 compliance framework Added control AZ-CMP-002 regarding cryptographic controls policy and its requirements. * feat: add AZ-CMP-002 to SOC2 compliance framework * fix: correct indentation in CIS AZ-CMP-002 entry * feat: add remediation playbook fix_az_cmp_002.sh to correct location This script enables Azure Disk Encryption on a specified virtual machine using a provided Key Vault for disk encryption. * Delete fix_az_cmp_002.sh * Feat/api deployment (#46) * feat: deploy API to Render with security hardening and CI/CD optimizations * feat: finalize Render deployment with security hardening and Gunicorn import fix * fix: GitHub Actions syntax and secret detection logic in deploy workflow * ix: harden scan trigger route with detailed error handling and remove redundant DB initialization * fix: implement global database connection management and harden all API routes * ix: prevent insecure smoke tests on main branch by enforcing JWT_SECRET presence and prevent CI false negatives in playbook check by enforcing non-empty glob match * fix: resolve Render startup crash and harden scan serialization against recursive objects * fix: add missing six and cryptography dependencies for Azure SDK compatibility * fix: increase CI wait time for Render build and add missing msrest dependencies * feat: integrate real subscription ID into smoke tests and CI/CD pipeline * feat: integrate real Azure_ ID's into smoke tests and CI/CD pipeline * feat: add root welcome route to confirm API status * fix: resolve specific CI credential flags in code and workflow while maintaining documentation standards * fix: resolve IndentationError in CI compliance cross-reference check * fix: resolve dependency issue and test on deployment * fix: resolve somke test TC-21 * fix: RUN_REAL_SCAN not set → TC-13/TC-14 skip → 21/21 pass for new live API url test * fix: scan.py deferred import from scanner.engine import ScanEngine was running before the subscription_id check * fix: restrict deploy triggers to dev and main, enable RUN_REAL_SCAN for maintainer CI, and update test plan documentation * feat: AZ-NET-011 Network Watcher not enabled in all regions (#42) * feat: add AZ-NET-011 Network Watcher rule, playbook and compliance mappings * fix: add missing AzureClient methods, SOC2 mapping and fix playbook region * fix: add SOC2 CC7.2 to FRAMEWORKS in az_net_011.py * feat: add AZ-DB-003 PostgreSQL Flexible Server SSL enforcement rule a… (#49) * feat: add AZ-DB-003 PostgreSQL Flexible Server SSL enforcement rule and playbook * fix: correct requirements.txt formatting for postgresqlflexibleserver * fix: correct postgresqlflexibleservers package name and version * fix: handle empty params gracefully and clean up playbook output * [RULE] AZ-CMP-003: VM without endpoint protection installed (#57) * feat: add scanner rule AZ-CMP-003 — VM without endpoint protection installed This script scans Azure VMs to check for the presence of recognized endpoint protection extensions. It logs findings for VMs without the required protection. * feat: add remediation playbook fix_az_cmp_003.sh This script installs endpoint protection on Azure VMs based on the operating system specified. It supports both Linux and Windows VMs. * feat: add AZ-CMP-003 to CIS compliance framework * feat: add AZ-CMP-003 to NIST compliance framework * feat: add AZ-CMP-003 to ISO27001 compliance framework * feat: add AZ-CMP-003 to SOC2 compliance framework * feat: add get_vm_extensions method to AzureClient Add method to retrieve VM extensions for a given VM. * fix: correct indentation and return type in get_vm_extensions * Add 1 more space in the code * add 4 space beofre def Add method to retrieve VM extensions for a given VM. * [DOCS] Add OpenShield learning and onboarding portal (#51) * docs: add OpenShield learning portal * Fix formatting for Learn OpenShield section --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> * refactor: reuse database connection per request using Flask g (#41) * fix: improve scan routes error handling and database reuse * fix: add database connection reuse and DATABASE_URL validation to score.py * fix: add database connection reuse, DATABASE_URL validation, and FileNotFoundError handling to compliance.py * fix: enforce JWT_SECRET environment variable, remove hardcoded default * ci: trigger fresh CI run * fix: all requirements - g.db naming, teardown, close() method * docs: add security policy, issue template, and README badges (#64) * feat: add rule AZ-KV-004 Key Vault purge protection disabled (#55) * feat: add rule AZ-KV-004 Key Vault purge protection disabled * fix: address PR review feedback for AZ-KV-004 - Add SOC2 CC9.1 mapping to FRAMEWORKS dict - Add AZ-KV-004 entries to all four compliance framework JSON files - Add set -euo pipefail to playbook - Add resource_group to metadata dict * feat: add AZ-STOR-005 geo-redundant storage rule (#74) - scanner/rules/az_stor_005.py: detects storage accounts using LRS or ZRS (non-geo-redundant) replication; flags them as MEDIUM severity - playbooks/cli/fix_az_stor_005.sh: CLI remediation to update storage account SKU to a geo-redundant option (Standard_GRS by default); validates target SKU against allowed geo-redundant values - compliance/frameworks/*.json: adds AZ-STOR-005 entry to CIS Azure Benchmark (3.1), NIST CSF (PR.IP-4), ISO 27001 (A.17.2.1), and SOC 2 (A1.2) Closes #71 Co-authored-by: Shaurya K Sharma * feat: add rule AZ-DB-004 SQL Server firewall allows all Azure services (#70) * feat: add rule AZ-DB-004 SQL Server firewall allows all Azure services - Add scanner rule az_db_004.py detecting SQL Servers with Allow Azure services firewall rule enabled - Add remediation playbook fix_az_db_004.sh - Add get_sql_server_firewall_rules method to AzureClient - Add AZ-DB-004 entries to all four compliance framework JSON files * fix: add get_sql_server_firewall_rules to AzureClient * fix: remove duplicate import, fix indentation, add return None to auditing policy * docs: add 6 README badges (#79) * feat: add AZ-KV-005 Key Vault certificate expiring within 30 days (#75) * Remove duplicate import of MonitorManagementClient * Add method to get Key Vault certificates Added a new method to list certificates in a Key Vault. * Add AZ-KV-005 rule for expiring Key Vault certificates This script scans Azure Key Vaults for certificates that are expiring within 30 days and do not have auto-renewal enabled. It logs findings and provides remediation steps. * Add script to enable auto-renewal for Key Vault certificate This script enables auto-renewal for an expiring Key Vault certificate by updating its policy. * Add controls for Azure Key Vault security measures * Add AZ-KV-005 control for certificate maintenance * Add controls for key management and availability * Add SOC 2 controls for Azure Key Vault risk mitigation * Fix indentation in get_key_vaults method * Add azure-keyvault-certificates dependency * Enhance script error handling with pipefail option * Refactor lifetime_actions assignment for clarity * Add control for expiring certificate maintenance Added a new control for certificate maintenance in Azure Key Vault. * fix: add missing comma in soc2.json after AZ-KV-005 entry * fix: add missing comma in iso27001.json after AZ-KV-005 entry * [RULE] AZ-CMP-004: VM without automatic OS patching enabled (#73) * Added az_cmp_004.py to check VM patching status This script checks Azure VMs for automatic OS patching status and collects findings for those without it enabled. * Added script to enable automatic OS patching for VMs This script enables automatic OS patching for both Windows and Linux VMs in Azure. It requires a resource group and VM name as input, defaulting to Windows if the OS type is not specified. * Add control for OS patching requirement in CIS benchmark * Add vulnerability management control to NIST CSF * Added control AZ-CMP-004 for vulnerability management * Added SOC 2 controls for endpoint protection and OS patching * Fix JSON formatting in cis_azure_benchmark.json * Fix JSON formatting in nist_csf.json * Improve error handling in fix_az_cmp_004.sh Updated script to use 'set -euo pipefail' for better error handling. * Update patching condition for Windows configuration Refine condition for patching approval based on patch mode. * Fix indentation and formatting in az_cmp_004.py * feat: add AI provider abstraction layer for Anthropic, Groq and Gemini (#89) * feat: initialise api/services package * feat: add AI provider abstraction layer for Anthropic, Groq and Gemini * fix: add module docstring to ai_provider.py Added a docstring explaining the purpose of the AI provider abstraction layer. * fix: make model configurable with sensible defaults per provider * Smoke Test Alginment after the recent changes to the Repository causing the Deployment CI failure (#88) * fix: test align smoke tests with API behavior and environment * test: deploy.yml run after smoke test alginment * fix: smoke test aligned after recent codebase changes * feat: add AZ-IDN-004 PIM not configured for admin roles rule and play… (#77) * feat: add AZ-IDN-004 PIM not configured for admin roles rule and playbook * fix: fetch Graph API token once and reuse headers for both API calls * fix: correct malformed JSON in cis_azure_benchmark.json for AZ-IDN-004 entry --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> * feat: add AI executive summary and remediation endpoint (#95) * feat: add AI insights endpoint * ci: scan only quoted-literal credential assignments --------- Co-authored-by: Shaurya K Sharma * feat(scanner): add AZ-NET-014 VNet peering gateway transit rule (#94) - Add scanner/rules/az_net_014.py to detect VNet peerings with allowGatewayTransit or useRemoteGateways enabled - Add get_vnet_peerings() and get_azure_firewalls() to azure_client.py - Add playbooks/cli/fix_az_net_014.sh remediation script - Update all 4 compliance framework JSONs with AZ-NET-014 mappings * feat: add AZ-NET-013 Azure Firewall VNet rule (#99) Co-authored-by: Shaurya K Sharma * Implement AI Q&A over scan findings (#98) Co-authored-by: Shaurya K Sharma * Feat/CVE correlation (#96) * fix: smoke test aligned after recent codebase changes * feat: add CVE correlation via MITRE NVD API * fix: ensure the run migration logic handles edge cases * fix: sync with dev after merged PRs, fix compliance duplication, indentaion and omttion of AZ-STOR-04 * fix: CVE prefix mappings, use legacy-only enrichment, clean up tests, and align CVE correlation docs. * fix: findings DB cleanup, AI title fallback, and persist CVE enrichment * feat: add RAG powered AI insights layer with Azure security skill embeddings (#97) * Create __init__.py * Implement OpenShield vector store builder This script builds the OpenShield knowledge base vector store for RAG AI insights by collecting rules and compliance documents, then embedding them into a vector store. * Add AI insights routes for summary, prioritisation, and Q&A * Implement knowledge retrieval from vector store This module retrieves relevant knowledge from the OpenShield vector store for retrieval-augmented generation (RAG). It includes error handling for missing vector stores and the chromadb dependency. * Register AI blueprint in the Flask app * Add chromadb version 0.4.24 to requirements * feat: add Azure security skills into knowledge base for RAG embedding * feat: wire Azure skill documents into embedding pipeline * Add sentence-transformers version 2.7.0 to requirements * ignore generated ai vectorstore directory * Refactor AI insights routes for clarity and updates * fix: deduplicate ai_bp and restore missing score_bp import in app.py * Refactor severity handling and update prompts * merge dev into feat/rag-ai-insights, resolve ai.py conflict * trigger CI * Remove AZ-CMP-003 and update AZ-NET-014 description Removed control AZ-CMP-003 related to unauthorized software detection and updated control AZ-NET-014 description for clarity. * feat: add AZ-NET-012 - NSG flow logs not enabled rule (#76) * ci: trigger fresh CI run * Dev (#50) * chore: add skeleton files and requirements * fix: remove embedded git repo * Core Structure Created * feat: build complete core — scanner engine, 10 rules, API, playbooks, compliance mappings, docs * docs: replace ASCII architecture with interactive Mermaid diagram * feat: Sentinel integration — ingest.py, 4 KQL rules, setup guide (#12) * feat: add sentinel/ingest.py — Log Analytics ingestion via HMAC-SHA256 * feat: add sentinel/__init__.py * feat: add KQL rule — HIGH severity finding detected * feat: add KQL rule — misconfiguration wave detection * feat: add KQL rule — new resource type critical detection * Delete sentinel/rules directory * Create rules * Delete sentinel/rules * Add KQL rule for high severity findings * Add Misconfiguration Wave detection rule * Add KQL rule for persistent misconfiguration detection * Add KQL rule for new critical resource types This rule identifies new resource types with critical findings that have occurred in the last 24 hours, excluding known types from the last 30 days. * Add script to generate test findings in JSON format This script generates test findings related to security compliance and saves them in a JSON file. * Add Sentinel integration test plan and results Added a comprehensive test plan for Sentinel integration, detailing test objectives, results, and acceptance criteria for various KQL rules and data ingestion. * docs: add sentinel integration setup guide Added a comprehensive setup guide for integrating Sentinel with Azure, covering prerequisites, workspace creation, activation, environment variable setup, ingestion, log verification, KQL rules deployment, and incident verification. * fix: add AZ-STOR-003 compliance mappings, correct NIST control to PR.DS-3 * docs: add real-world breach scenarios for all 10 starter rules (#15) * feat: add AZ-KV-002 key vault public access rule and remediation playbook (#14) * docs: update README with rule count, roadmap progress and contributors * feat: add network security rules AZ-NET-003 to AZ-NET-010 (#16) * Add az_net_003.py to check NSG rules for port 443 This script detects Network Security Groups (NSGs) with unrestricted inbound access on port 443 and provides remediation guidance. * Add AZ-NET-004 rule for empty NSG detection This script detects Network Security Groups (NSGs) that have no custom security rules configured, providing details for remediation. * Add AZ-NET-005 rule for DDoS protection check This script detects virtual networks in Azure that do not have DDoS protection enabled and provides remediation steps. * feat: add rule AZ-NET-006 — public IP unassociated with any resource This rule detects public IP addresses that are not associated with any resource, providing details for remediation. * feat: add rule AZ-NET-007 — Application Gateway without WAF enabled This rule detects Application Gateways that do not have WAF enabled, logging findings and providing remediation steps. * feat: add rule AZ-NET-008 — load balancer with no backend pool This rule detects load balancers in Azure that are not configured with a backend pool, indicating potential misconfiguration or unnecessary costs. * feat: add rule AZ-NET-009 — VPN gateway using outdated IKE version This script detects VPN gateways using the outdated IKEv1 protocol and provides remediation steps to migrate to IKEv2. * feat: add rule AZ-NET-010 — subnet with no NSG attached This script detects subnets in Azure that do not have a Network Security Group (NSG) attached, logging findings and providing remediation guidance. * feat: add playbook fix_az_net_003.sh This script updates the NSG rule to restrict inbound traffic on port 443 to a specified IP range. * feat: add playbook fix_az_net_004.sh This script adds a default deny-all inbound rule to a specified NSG. * feat: add playbook fix_az_net_005.sh This script enables DDoS protection on a specified virtual network in Azure. It checks for required parameters and provides usage instructions if they are missing. * feat: add playbook fix_az_net_006.sh This script deletes unassociated public IP addresses in Azure. * feat: add playbook fix_az_net_007.sh This script enables WAF on an Application Gateway, ensuring compliance with the AZ-NET-007 rule. * feat: add playbook fix_az_net_008.sh Script to remediate AZ-NET-008 by deleting empty load balancers. * feat:add script to update VPN connection to IKEv2 This script updates a VPN connection to use IKEv2, ensuring compliance with the AZ-NET-009 rule. * feat: add playbook fix_az_net_010.sh This script attaches a specified network security group to a given subnet in a virtual network, ensuring compliance with the AZ-NET-010 rule. * Clarify description and add note for public-facing services Updated the description to clarify the risk of exposing port 443 and added a note regarding public-facing services. * Change severity level from MEDIUM to HIGH * fix: AZ-NET-005 severity changed to LOW — DDoS Standard high cost on small subscriptions * Add note about NetworkManagementClient usage Added a note regarding the creation of NetworkManagementClient directly and suggested a follow-up for consistency. * Add note about NetworkManagementClient usage Added a note regarding the use of NetworkManagementClient and suggested a follow-up for consistency. * Add additional security controls to CIS Azure benchmark * Refine control descriptions in nist_csf.json Updated descriptions for various controls to enhance clarity and specificity regarding remote access management, data protection, and security measures. * fix: add AZ-NET-003 to AZ-NET-010 to ISO27001 compliance framework Updated descriptions for various controls to clarify compliance requirements and improve security guidance. --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> * Feat/az stor 003 (#21) * feat: add rule AZ-STOR-003 storage lifecycle policy check * feat: add rule AZ-STOR-003 storage lifecycle policy check * docs: add SOC 2 Type II compliance framework mapping (#33) * docs: add SOC 2 Type II compliance framework mapping for all 20 rules Added SOC 2 Type II framework with detailed controls for security measures and compliance requirements. * feat: add soc2 to FRAMEWORK_FILE_MAP in finding.py add soc2.json to FRAMEWORK_FILE_MAP in finding.py * feat: add soc2 to SUPPORTED_FRAMEWORKS in compliance.py Added 'soc2' to the list of supported compliance frameworks. * Add SOC 2 controls for data protection and management * Refactor/azure client network methods (#22) * refactor: add get_virtual_networks() and get_public_ip_addresses() to AzureClient * Refactor DDoS protection check to use azure_client * refactor: AZ-NET-006 now uses azure_client.get_public_ip_addresses() * feat: add CI pipeline with 6 automated checks (#34) - Python syntax check on all rule files - Rule structure validation (RULE_ID, SEVERITY, FRAMEWORKS) + RULE_ID uniqueness - Hardcoded credential scan - Playbook existence + bash syntax check for every rule - Compliance JSON validation for all four framework files (inc. soc2.json) - API syntax check - Compliance vs rule cross-reference check - CI summary step with per-check pass/fail table (if: always) - Fix duplicate DESCRIPTION assignment in az_net_003.py - Add pyyaml to requirements.txt for local YAML validation - Add docs/ci-pipeline.md with local run commands and design rationale - Update CI_PIPELINE_GUIDE.md with final PR description Closes #30 * docs: update .github/ISSUE_TEMPLATE/new_rule.md to reflect current codebase state * docs: update .github/PULL_REQUEST_TEMPLATE.md to reflect current codebase state * docs: update CONTRIBUTING.md to reflect current codebase state * docs: update README.md to reflect current codebase state * docs: update compliance/frameworks/iso27001.json to reflect current codebase state * docs: update compliance/frameworks/nist_csf.json to reflect current codebase state * docs: update docs/adding-a-rule.md to reflect current codebase state * docs: update docs/architecture.md to reflect current codebase state * docs: update docs/az-stor-003-test-plan.md to reflect current codebase state * docs: update docs/azure-setup.md to reflect current codebase state * docs: update docs/ci-pipeline.md to reflect current codebase state * docs: update docs/sentinel-setup.md to reflect current codebase state * docs: update sentinel/TEST_PLAN.md to reflect current codebase state * docs: update docs/api-reference.md to reflect current codebase state * docs: update docs/rules-reference.md to reflect current codebase state * docs: update README.md for professional open source style * docs: update CONTRIBUTING.md for professional open source style * docs: update docs/adding-a-rule.md for professional open source style * docs: update deployment guide to use Render instead of Azure App Service * feat: add rule AZ-STOR-004 storage account diagnostic logging check (#39) * feat: add rule AZ-STOR-004 storage account diagnostic logging check Detects Azure storage accounts where diagnostic logging is not fully enabled on blob, queue, or table services. Emits one finding per non-compliant service (StorageRead, StorageWrite, StorageDelete must all be enabled). Adds get_storage_service_logging() to AzureClient using MonitorManagementClient. Includes remediation playbook that enables all three services in one run. Frameworks: CIS 3.3, NIST DE.CM-7, ISO 27001 A.12.4.1 * chore: add AZ-STOR-004 compliance mappings --------- Co-authored-by: Shaurya K Sharma * feat: add rule AZ-IDN-003 Adds scanner rule AZ-IDN-003 detecting Entra ID (#48) * feat: add scanner rule AZ-IDN-003 — guest user invitations not restricted to admins * feat: add remediation playbook fix_az_idn_003.sh This script restricts guest user invitations to only admins and users with the Guest Inviter role in Azure Active Directory. * feat: add AZ-IDN-003 to CIS compliance framework Added control for guest invite restrictions to enhance security. * feat: add AZ-IDN-003 to NIST compliance framework * feat: add AZ-IDN-003 to ISO27001 compliance framework Added control AZ-IDN-003 for user registration and de-registration process. * feat: add AZ-IDN-003 to SOC2 compliance framework * feat: add rule AZ-CMP-002 — VM disk not protected by CMK or ADE (#47) * feat: add scanner rule AZ-CMP-002 — VM disk not protected by CMK or ADE This script detects virtual machines whose disks use platform-managed encryption only and provides findings for compliance with CIS 7.2. * feat: add remediation playbook fix_az_cmp_002.sh This script enables Azure Disk Encryption on a specified virtual machine using a Key Vault for the disk encryption key. * feat: add AZ-CMP-002 to CIS compliance framework Added a new control for OS disk encryption requirements. * feat: add AZ-CMP-002 to NIST compliance framework * feat: add AZ-CMP-002 to ISO27001 compliance framework Added control AZ-CMP-002 regarding cryptographic controls policy and its requirements. * feat: add AZ-CMP-002 to SOC2 compliance framework * fix: correct indentation in CIS AZ-CMP-002 entry * feat: add remediation playbook fix_az_cmp_002.sh to correct location This script enables Azure Disk Encryption on a specified virtual machine using a provided Key Vault for disk encryption. * Delete fix_az_cmp_002.sh * Feat/api deployment (#46) * feat: deploy API to Render with security hardening and CI/CD optimizations * feat: finalize Render deployment with security hardening and Gunicorn import fix * fix: GitHub Actions syntax and secret detection logic in deploy workflow * ix: harden scan trigger route with detailed error handling and remove redundant DB initialization * fix: implement global database connection management and harden all API routes * ix: prevent insecure smoke tests on main branch by enforcing JWT_SECRET presence and prevent CI false negatives in playbook check by enforcing non-empty glob match * fix: resolve Render startup crash and harden scan serialization against recursive objects * fix: add missing six and cryptography dependencies for Azure SDK compatibility * fix: increase CI wait time for Render build and add missing msrest dependencies * feat: integrate real subscription ID into smoke tests and CI/CD pipeline * feat: integrate real Azure_ ID's into smoke tests and CI/CD pipeline * feat: add root welcome route to confirm API status * fix: resolve specific CI credential flags in code and workflow while maintaining documentation standards * fix: resolve IndentationError in CI compliance cross-reference check * fix: resolve dependency issue and test on deployment * fix: resolve somke test TC-21 * fix: RUN_REAL_SCAN not set → TC-13/TC-14 skip → 21/21 pass for new live API url test * fix: scan.py deferred import from scanner.engine import ScanEngine was running before the subscription_id check * fix: restrict deploy triggers to dev and main, enable RUN_REAL_SCAN for maintainer CI, and update test plan documentation * feat: AZ-NET-011 Network Watcher not enabled in all regions (#42) * feat: add AZ-NET-011 Network Watcher rule, playbook and compliance mappings * fix: add missing AzureClient methods, SOC2 mapping and fix playbook region * fix: add SOC2 CC7.2 to FRAMEWORKS in az_net_011.py * feat: add AZ-DB-003 PostgreSQL Flexible Server SSL enforcement rule a… (#49) * feat: add AZ-DB-003 PostgreSQL Flexible Server SSL enforcement rule and playbook * fix: correct requirements.txt formatting for postgresqlflexibleserver * fix: correct postgresqlflexibleservers package name and version * fix: handle empty params gracefully and clean up playbook output --------- Co-authored-by: Tanvir Farhad Co-authored-by: PARTH J ROHIT Co-authored-by: Ritik Sah Co-authored-by: Shaurya K Sharma Co-authored-by: Shaurya K Sharma Co-authored-by: Mahfuzur Rahman Emon * refactor: reuse database connection per request using Flask g (#41) * fix: improve scan routes error handling and database reuse * fix: add database connection reuse and DATABASE_URL validation to score.py * fix: add database connection reuse, DATABASE_URL validation, and FileNotFoundError handling to compliance.py * fix: enforce JWT_SECRET environment variable, remove hardcoded default * ci: trigger fresh CI run * fix: all requirements - g.db naming, teardown, close() method * fix: update az_net_012.py to match az_cmp_003 pattern and add set -euo pipefail to bash script * fix: correct az_net_012.py signature, add set -euo pipefail, add AZ-NET-012 to all compliance files * fix: correct az_net_012.py to match az_cmp_003 pattern --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> Co-authored-by: Tanvir Farhad Co-authored-by: PARTH J ROHIT Co-authored-by: Ritik Sah Co-authored-by: Shaurya K Sharma Co-authored-by: Shaurya K Sharma Co-authored-by: Mahfuzur Rahman Emon * fix: resolve CodeQL warnings in embed.py and test files * feat(frontend): build complete 7-page security dashboard (#111) * Basic components and pages with dummy data * feat(frontend): build complete 7-page security dashboard Complete React 18 + Vite frontend for OpenShield security platform. Pages (7): - Monitoring — security score gauge, trend chart, findings distribution, issues by resource group, category scores - Discovery — resource table with issue counts, risk filters, category grouping, resource group filtering, clickable category cards - Prioritization — risk vs effort matrix, ranked list with quick remediation preview, all 25 action items; click-to-select syncs matrix + action items + remediation panel - Detailed Scan — findings list with playbook tabs (portal/CLI/validation), navigates from Prioritization with context banner - Compliance — CIS/NIST/ISO27001/SOC2 framework cards, controls table, comparison trend chart, CSV/JSON export - Drift — configuration change timeline, ADDED/REMOVED/MODIFIED events with before/after values, who changed it and when - AI Assistant — 3-column layout (findings picker, chat, suggestions + CVE analysis + executive summary); AI chat wired to aiApi.js with smart mock responses; finding context passed from Scan page API service layer (src/utils/api.js): - Demo/Live mode toggle persisted in localStorage - JWT token bootstrap in App.jsx - Health check on startup with auto-fallback to demo mode - Real fetch calls with mock fallback for every endpoint: /api/score, /api/findings, /api/findings/:id, /api/findings/:id/playbook, /api/resources, /api/prioritization, /api/drift, /api/scans, /api/scans/trigger, /api/scans/:id, /api/compliance/cis|nist|iso27001 - snake_case → camelCase normalisation for all backend responses - Separate aiApi.js for AI endpoints with smart mock responses Header features: - Run Scan button with live polling (4s interval, 5-min timeout, elapsed timer) - Demo/Live badge with connection test before switching - Error popup if backend is unreachable Design system: - Tailwind CSS v3 with custom tokens (brand, severity, bg-dark, status) - Dark mode via class strategy, persisted in localStorage - Fully responsive — mobile hamburger drawer, stacked layouts on sm - Dot-pattern background, soft shadows, consistent 4px grid Mock data: - 8 api.*.json files matching exact backend response schema - API_ENDPOINTS.txt — backend contract document with implementation status, database schema, seed data, and endpoint ordering guide Co-Authored-By: Claude Sonnet 4.6 * feat(frontend): wire live backend, fix JWT auth, add Vercel deployment config - Fix JWT: read VITE_JWT_TOKEN env var so live API calls authenticate correctly (was sending plain string 'dev-demo-token' which backend rejected as invalid JWT) - Add vercel.json with SPA rewrites so /monitoring, /scan etc don't 404 - Monitoring page now fetches real score + findings in live mode and computes stats/distribution/resource-group breakdown from actual backend data - Run Scan button shows subscription ID input in live mode (optional — backend falls back to AZURE_SUBSCRIPTION_ID env var if blank) - api.js: no silent localhost fallback in production builds (fails loudly if VITE_API_URL is not set) --------- Co-authored-by: Claude Sonnet 4.6 * Feat/jwt secret prod fail closed (#117) * fix: smoke test aligned after recent codebase changes * feat: fail closed on insecure JWT_SECRET in production * fix: rename _DEFAULT_JWT_SECRET to avoid CI credential scanner false positive * feat: AI-004 RAG Pipeline - Document Ingestion and Vector Store (#104) * feat: add AZ-IDN-004 PIM not configured for admin roles rule and playbook * feat: add RAG pipeline with document loader, chunker, embedder, ChromaDB vector store and Flask API routes * fix: remove duplicate ai files, restore deleted compliance rules, revert requirements to chromadb 0.4.24 * fix: update gitignore to use ai/vectorstore/ and clean up README references * fix: add missing newline at EOF in compliance JSON files * Potential fix for pull request finding 'Unused import' Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> * feat: add PQC compliance mappings, azure client methods and dependencies --------- Co-authored-by: Tanvir Farhad Co-authored-by: PARTH J ROHIT Co-authored-by: Ritik Sah Co-authored-by: Shaurya K Sharma Co-authored-by: Shaurya K Sharma Co-authored-by: Mahfuzur Rahman Emon Co-authored-by: Safid Nadaf <137755124+safidnadaf@users.noreply.github.com> Co-authored-by: Abdulbosit Abdurazzakov <2d9c6kh58x@privaterelay.appleid.com> Co-authored-by: Mahfuzur Rahman Emon Co-authored-by: Prayas Gautam <159550781+vogonPrayas@users.noreply.github.com> Co-authored-by: Claude Sonnet 4.6 Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> * docs: update OpenShield Learn portal * docs: update OpenShield Learn portal * docs: redirect Learn site root * docs: add OpenShield Learn link to README * docs: update OpenShield Learn portal --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> Co-authored-by: Tanvir Farhad Co-authored-by: Ritik Sah Co-authored-by: Shaurya K Sharma Co-authored-by: Shaurya K Sharma Co-authored-by: Mahfuzur Rahman Emon Co-authored-by: Safid Nadaf <137755124+safidnadaf@users.noreply.github.com> Co-authored-by: Abdulbosit Abdurazzakov <2d9c6kh58x@privaterelay.appleid.com> Co-authored-by: Mahfuzur Rahman Emon Co-authored-by: Prayas Gautam <159550781+vogonPrayas@users.noreply.github.com> Co-authored-by: Claude Sonnet 4.6 Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> * feat(tests): MockAzureClient rule regression test harness — 7 rules offline (#124) * feat: initialise tests/helpers package * feat: add MockAzureClient test helper Introduced MockAzureClient for offline testing of Azure-related functionality. * feat: add mock_azure and subscription_id fixtures to conftest Add fixtures for mock Azure client and subscription ID * feat: add storage rule regression tests for AZ-STOR-001 and AZ-STOR-002 This file contains regression tests for storage rules AZ-STOR-001 and AZ-STOR-002, ensuring compliance checks for public access and HTTPS-only settings. * feat: add network rule regression tests for AZ-NET-001 and AZ-NET-002 Add regression tests for AZ-NET-001 and AZ-NET-002 rules to validate compliance and non-compliance scenarios for NSGs. * feat: add identity rule regression tests for AZ-IDN-001 Added regression tests for AZ-IDN-001 rule to validate compliance and non-compliance scenarios. * feat: add key vault rule regression tests for AZ-KV-002 Added regression tests for AZ-KV-002 rule to validate Key Vault compliance based on public access and private endpoint configurations. * feat: add database rule regression tests for AZ-DB-004 Add regression tests for AZ-DB-004 rule compliance. * Add pytest dependencies and rule regression test CI step * Add rule regression tests to CI workflow * Add DATABASE_URL environment variable for tests * Refactor imports and update JWT handling in tests * Remove unused jwt import from conftest.py * Enhance comments for hardcoded credential scan Added comments to clarify credential scanning patterns. * AZ-IDN-005 to AZ-IDN-009 — Entra ID identity scanner rules (#109) * Add AZ-IDN-005 rule for guest user role detection This script detects guest users assigned to high privilege roles in Entra ID and logs findings for remediation. * Add AZ-IDN-006 rule for client secret expiry check Implement AZ-IDN-006 rule to detect service principal client secrets older than 90 days or without expiry. The rule includes logging, fetching applications from Graph API, and evaluating credentials. * Add AZ-IDN-007 rule for MFA registration detection This rule detects active user accounts in Entra ID that do not have multi-factor authentication methods registered, highlighting potential security vulnerabilities. * Add AZ-IDN-008 rule for RBAC role scanning This script detects custom RBAC roles with wildcard or overly broad permissions at the subscription scope and provides remediation steps. * Add AZ-IDN-009 rule for role assignment alerts This rule checks for the absence of activity log alerts for role assignment changes in Azure subscriptions, logging findings if no alerts are configured. * Add remediation playbook for AZ-IDN-005 This script provides a remediation playbook for removing high privilege roles from guest users in Entra ID, including usage instructions and role assignment fetching. * Add remediation playbook for AZ-IDN-006 This script provides a remediation playbook for rotating service principal client secrets older than 90 days. It includes usage instructions and steps for listing, resetting credentials, and migrating to managed identities. * Add MFA enforcement remediation playbook script This script provides a remediation playbook for enforcing MFA registration for users without MFA in Entra ID. It includes steps to identify users and create a Conditional Access policy. * Add remediation playbook for AZ-IDN-008 This script provides a playbook for remediating custom RBAC roles with wildcard permissions at the subscription scope, guiding users through listing, reviewing, and updating roles. * Add script to create activity log alert for role changes This script creates an activity log alert for role assignment changes to detect privilege escalation in real time. * Add new controls for Azure security compliance * Add new NIST CSF controls for identity and access management * Add ISO 27001 controls for security compliance Added new controls for privileged access management, password management, secure log-on procedures, and event logging to comply with ISO 27001 standards. * Add SOC 2 controls for logical access and monitoring * Potential fix for pull request finding 'Empty except' The fix is right! Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> * Potential fix for pull request finding 'Unused variable, import, function or class' Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> * Implement threat simulation prompt builder (#138) Add a function to build a threat simulation prompt based on findings and context. * docs: add frontend API validation guide (#134) Co-authored-by: Shaurya K Sharma * fix(compliance): align rule reference and framework mappings (#130) * feat: implement asynchronous scan execution with background worker (#129) * feat: implement asynchronous scan execution with background worker * chore: async scan architecture with 100% verified test suite * feat: complete transition to async scan architecture with verified E2E suite and docs * fix: addressed the requested changes * fix: address security and architecture issues in async scan processing - Sanitize worker error messages to prevent sensitive exception details from being exposed through the public API - Revert unrelated schema and search_path changes to maintain compatibility with existing public-schema deployments - Add column to preserve as the original queue timestamp - Improve migration logic to correctly backfill historical scans and repair incorrect statuses - Update worker tests to reflect generic error handling and the new atomic scan-claiming workflow * feat(scanner): add AZ-NET-015 public DNS zone enumeration rule (#106) * feat(scanner): add AZ-NET-015 public DNS zone enumeration rule - Add scanner/rules/az_net_015.py to detect public DNS zones - Add get_dns_zones() to azure_client.py using DnsManagementClient - Add playbooks/cli/fix_az_net_015.sh remediation script - Add azure-mgmt-dns==8.0.0 to requirements.txt - Update all 4 compliance framework JSONs with AZ-NET-015 mappings * feat(scanner): add get_dns_record_sets to AzureClient * feat(scanner): rewrite AZ-NET-015 to detect RFC1918 IPs and internal hostnames in public DNS zones * feat(compliance): add AZ-NET-015 mappings to all four framework JSON files * fix: scope posture endpoints to latest completed scan (#145) * Update finding.py total_findings > 0 skips any scan where 0 issues were found. So after you fix all misconfigs and run a clean scan, the dashboard ignores it and keeps showing the old dirty scan. status = 'completed' picks the latest scan that finished successfully, whether it found 0 things or 100 things. * Update finding.py * Update ci.yml * Create test_clean_scan.py all confirmed passing locally. Zero real DB or Azure calls pure mock. * Update ci.yml * Update finding.py * Fix: Make Flask app test-safe and run full pytest suite in CI (#143) * fix: skip DB migrations when DATABASE_URL is unset and add full pytest step to CI * fix: add PYTEST to CI Summary env section * feat: Integrate Azure Offensive Skills and Dynamic AI Grounding (#137) * feat: integrate azure offensive skills with dynamic grounding and metadata standardization * feat(ai): harden RAG grounding logic and stabilize vectorstore rebuild flow * fix(ci): decouple app from database during test collection and execution * fix(ci): prevent side-effect create_app() call during pytest collection * fix(tests): mock database manager in jwt config integration tests --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> * feat(auth): require JWT for GET /api/* endpoints with optional public demo mode (#144) * Update public access paths and database migration logic Refactor public access logic and improve database migration handling. * Add tests for JWT authentication middleware This file contains tests for JWT authentication middleware, including both production and demo modes. It tests various endpoints for JWT requirements and public access. * Enhance API reference with authentication details Added authentication details and public demo mode information to the API reference. * Add auth tests to regression test suite * Remove DATABASE_URL from CI workflow Removed DATABASE_URL environment variable from rule regression tests. * Update ci.yml * fix: mock DatabaseManager in test_auth.py fixtures to prevent CI DB connection * fix(scanner): improve AZ-NET-008 with SOC2 mapping and azure_client abstraction (#108) * CI: parallel jobs, lint/format gate, security scanning, coverage (#155, #156) (#165) * ci: parallel CI jobs with lint, security scanning, coverage and branch-flow gates (#155, #156) * ci: attach SBOM to releases, pin CI node to 22, harden release workflow (#156) * Fix async scan state recovery (#169) * feat(infra): observability layer — structured logs, request IDs, metrics, readiness probe (#167) Implements issue #159 (INFRA 6). - api/observability.py: shared module with JSON logging (python-json-logger), optional Sentry init (only when SENTRY_DSN set), request-ID middleware, Prometheus metrics, and the /metrics endpoint. - api/app.py: wire observability middleware first; split /health (liveness, no DB) from /ready (DB connectivity → 200/503); echo X-Request-ID; include request_id in JSON error responses and auth failures; /ready + /metrics public. - api/models/finding.py: add DatabaseManager.ping() for the readiness probe. - scanner/worker.py: shared JSON logging, conditional Sentry, scan_id as a structured log field, scan success/failure counters, scan duration, queue depth. - scanner/engine.py: increment per-rule error counter when a rule raises. - scanner/nvd_client.py, api/services/ai_provider.py: record external-call latency. - requirements.txt: add prometheus-client, python-json-logger, sentry-sdk. - tests/test_observability.py: probes, /metrics, request IDs, auth request_id, conditional Sentry, worker metrics. No metric is labelled with request_id, scan_id, subscription_id, resource_id, error_message or user input. Co-authored-by: Shaurya K Sharma * fix(compliance): correct duplicate CIS control mappings, TLS version compare, Graph pagination (#166) * fix(compliance): correct duplicate CIS control mappings, TLS version compare, Graph pagination - Fix AZ-CMP-001 sharing CIS control 7.2 with unrelated AZ-CMP-002 - De-duplicate 13 rules that shared CIS control_id values across cis_azure_benchmark.json, their rule files, docs, and the website - Replace lexicographic TLS version comparison in az_pqc_001 with a numeric parser so "1.10" is no longer misread as below "1.3" - Follow @odata.nextLink pagination in get_conditional_access_policies instead of dropping all results past the first page * style: apply ruff format to new compliance/pagination tests * build(deps): bump react-router (#148) Bumps the npm_and_yarn group with 1 update in the / directory: [react-router](https://github.com/remix-run/react-router/tree/HEAD/packages/react-router). Updates `react-router` from 7.15.0 to 7.18.0 - [Release notes](https://github.com/remix-run/react-router/releases) - [Changelog](https://github.com/remix-run/react-router/blob/main/packages/react-router/CHANGELOG.md) - [Commits](https://github.com/remix-run/react-router/commits/react-router@7.18.0/packages/react-router) --- updated-dependencies: - dependency-name: react-router dependency-version: 7.18.0 dependency-type: indirect dependency-group: npm_and_yarn ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * build(deps-dev): bump vite (#147) Bumps the npm_and_yarn group with 1 update in the /frontend directory: [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite). Updates `vite` from 8.0.14 to 8.0.16 - [Release notes](https://github.com/vitejs/vite/releases) - [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite/commits/v8.0.16/packages/vite) --- updated-dependencies: - dependency-name: vite dependency-version: 8.0.16 dependency-type: direct:development dependency-group: npm_and_yarn ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * docs: add Azure scanner validation docs (#142) * fix: disable auto deploy to Render, manual trigger only * fix: ruff auto fixes * fix: resolve CodeQL high findings - XSS innerHTML, clear text logging and key storage * chore: add CODEOWNERS, issue templates, Docker setup and autonomous CI workflows * fix: raise dependency review threshold to critical only * fix: upgrade vulnerable dependencies flagged by pip-audit and npm audit * fix: revert dependency review threshold back to high * fix: use python:3.11-slim-bookworm base image to reduce Trivy vulnerabilities * fix: upgrade jaraco.context, transformers and wheel to fix Trivy HIGH findings * feat(db): implement Alembic migrations (#164) * feat(db): implement Alembic migrations (#158) * ci: validate Alembic migrations in backend tests * fix: remediate container scan vulnerabilities (#175) * Reliability fixes: score 500, DB pooling, async CVE enrichment, thread-safe rate limit (#162) * fix(reliability): score endpoint 500, DB pooling, async CVE enrichment, thread-safe rate limit Closes #150. - REL-001: remove duplicate GROUP BY in get_score() that made /api/score always return 500 - REL-002: replace fragile INTERVAL '%s minutes' string substitution with make_interval(mins => %s) - REL-003: DatabaseManager now borrows connections from a shared psycopg2 connection pool per DSN (DB_POOL_MAX_CONN, default 10) instead of opening a new connection per request - REL-004: POST /api/scans//enrich now runs CVE enrichment in a background thread and returns 202 immediately, instead of blocking on synchronous NVD lookups until the request times out - REL-005: lock-guard the NVD client's rate-limit check so concurrent callers can't fire requests closer together than the allowed gap - Fix a bug found during review: a failed enrichment write could leave the connection in an aborted-transaction state, silently swallowing the follow-up FAILED status update and leaving the scan stuck at ENRICHING forever; now rolls back first * fix(tests): consolidate duplicate module import style flagged by code-quality bot Both test_database_manager_reliability.py and test_nvd_client.py imported scanner/api modules with both 'import X as x' and 'from X import y' forms. Consolidated to one form each; test_nvd_client.py switches to string-path mock.patch() targets instead of importing the module object, avoiding the need to touch ~15 pre-existing call sites. * fix(scanner): encapsulate NVD rate limiter state to resolve unused-global false positive Replaces the bare module-level _last_request_time global (mutated via the global keyword) with a small _RateLimiter class holding the timestamp and lock as instance state. Same behavior, but removes the pattern the code-quality bot's static analysis was misreading as an unused global (it couldn't see the value is read by the next invocation of the same function via module state). * style: apply ruff format to satisfy new CI lint gate * fix(reliability): restore attempt-count check in recover_stale_scans The "mark failed" query lost its COALESCE(attempt_count, 1) >= %s clause during an earlier merge, while still passing 2 params to a query with only 1 placeholder — this would raise at runtime against a real database and would mark stale scans failed on their first timeout instead of after max_attempts retries. Restore the clause to match the tested, correct version. Also drop the now-superseded REL-002 test, whose single-query assumptions predate the retry-attempt feature; equivalent coverage now lives in tests/test_async_scan_persistence.py. * fix: remove dead run_migrations() call from create_app() A previous merge auto-resolved cleanly across files but left this call site stranded: api/models/finding.py dropped run_migrations() (schema is now Alembic-managed, applied via startup.sh) while api/app.py still called it whenever DATABASE_URL was set. Git's merge saw no conflict because the removal and the call site were in different files, but the result crashed create_app() with AttributeError in any environment with a real DATABASE_URL configured (e.g. CI's Postgres service), which is exactly why this passed locally (no DATABASE_URL set) but failed in CI. * test: add comprehensive validation coverage (#146) * test: add scanner rule and engine validation coverage Expand scanner rule regression coverage so all 45 rules have dedicated compliant and non-compliant cases (includes az_net_015). Add ScanEngine integration tests for rule loading, score consistency, and rule-failure isolation. Extend MockAzureClient test support only; no production code is changed. Full suite: 170 passed. Rule regression slice: 92 passed. Engine integration: 4 passed. Note: AZ-NET-009 and AZ-NET-012 tests validate intended isolated rule logic. The production integration defects discovered during validation are documented separately in the validation report. * docs: add comprehensive validation report Document the full OpenShield validation pass across environment setup, static checks, backend tests, scanner rules, engine integration, local API smoke tests, frontend build, AI/RAG, CVE/NVD, Sentinel review, security checks, documentation accuracy, and live deployment status. The report records remaining follow-up issues including AZ-NET-009, AZ-NET-012, AI chunker syntax failure, Sentinel field mapping mismatch, stale documentation counts, dependency CVEs, and deferred Azure/Sentinel live validation. * test: relax engine rule-count assertions to >= 45 Future rule additions should not break the engine integration tests. Assert at least the current 45-rule coverage exists rather than the exact total (addresses reviewer feedback). * test: finalize validation coverage for merge * test: apply ruff format and line-length fixes to validation tests * infra 7 : Terraform for Render/Vercel + GitHub OIDC for Azure credentials (#176) * docs: add design spec for Terraform IaC + Azure OIDC (issue #160) * docs: add implementation plan for Terraform IaC + Azure OIDC (issue #160) * infra: add Terraform provider/backend skeleton for Render and Vercel * infra: define Render Postgres, web service, and shared secrets env group * infra: define Vercel projects for the dashboard and website * infra: add Terraform outputs and module README * ci: add Terraform fmt/validate/plan workflow for infra PRs * ci: authenticate to Azure via OIDC instead of a long-lived client secret * docs: document one-time Azure AD federated credential setup for OIDC * docs: update secrets table for OIDC, add secrets inventory doc * Security hardening: body size limit, Gemini key header, AI rate limiting, playbook path traversal (#161) * fix(security): body size limit, Gemini key in header, AI rate limiting, playbook path traversal guard Closes #149. - SEC-002: cap request bodies at 2MB with a JSON 413 handler - SEC-003: send the Gemini API key via x-goog-api-key header instead of a URL query param, so it never leaks into logs - SEC-004: add a lightweight in-memory rate limiter (20 req/min/IP) on all AI endpoints - SEC-005: validate rule_id and confirm the resolved script path stays inside playbooks/cli/ before reading it - SEC-001 was already fixed on dev via #144; added a regression test to lock it in * fix(security): back rate limiter with Postgres, trust Render's proxy hop for client IP - Merge latest dev (ruff lint/format CI gate) and reformat the one flagged file - Replace the in-memory rate limiter with a Postgres-backed shared counter (rate_limit_hits table + advisory transaction lock) so all gunicorn worker processes enforce one real limit instead of each having its own counter - Add ProxyFix so request.remote_addr reflects the real client behind Render's reverse proxy instead of collapsing every caller into one IP - Reuse the existing g.db connection instead of a second untracked one, so it's closed by the app's existing teardown handler instead of leaking - Refuse (503) instead of silently and permanently disabling rate limiting when DATABASE_URL is unset, and roll back on a mid-transaction error * fix(tests): use single import style for api.rate_limit * Infra: add deterministic Render deploy pipeline and separate worker services (#172) * infra: add deterministic Render deploy pipeline * infra: make Render deploy workflow manual * fix(deploy): coordinate API and worker releases * fix(deploy): add resilient Render polling * test(deploy): cover coordinated deployment failures * docs(deploy): document dual-service Render releases * fix(deploy): avoid logging dispatch input * fix(deploy): correct rollback path and Render web configuration * docs(deploy): retire obsolete Render deployment guide --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> * fix(security): drop credential key_id from AZ-IDN-006 debug logging (#184) app_id/key_id are Azure AD identifiers, not the secret value itself (Microsoft Graph never returns password credential secret text after creation) — but key_id isn't needed to diagnose a malformed endDateTime either way, so drop it from the log line rather than argue the classification. Fixes #178 (CodeQL: clear-text logging of sensitive information, both findings — same log statement). * fix(security): resolve all high/critical CodeQL findings (#177, #179, #180) (#183) * fix(security): validate embed URLs by origin instead of substring match toEmbedUrl()'s fallback branch used raw.includes(...) to check for a known-safe embed URL, then returned the unvalidated input unmodified. A crafted string containing the substring anywhere could pass the check while breaking out of the iframe's src="..." attribute it gets interpolated into unescaped, injecting arbitrary markup. Validate via new URL(raw).hostname against an exact allowlist instead, and escape the result at every interpolation site as defense in depth. Also escape the two playground select-field values that were concatenated into an HTML-shaped string unescaped. Fixes #179 (CodeQL: DOM text reinterpreted as HTML x3, incomplete URL substring sanitization x1). * fix(security): move AI provider API key to in-memory-only storage A prior fix for this same CodeQL alert removed the localStorage.setItem call for the user's bring-your-own AI provider key but left the getter/isConfigured() reading from the now-permanently-empty key, silently breaking every AI feature (chat, summary, insights, prioritisation all gated behind isConfigured()). Store the key in a module-scoped variable instead of any browser storage. It never survives a page reload (the standard, expected trade-off for a secret that must not persist), but the feature works again and the key is never written to localStorage/sessionStorage. provider/model (not secret) still persist in localStorage as before. Fixes #180 (CodeQL: clear text storage of sensitive information). * fix(security): stop leaking exception details in API error responses Every affected route returned str(exc) (or an f-string embedding it) directly in the JSON response body. Some catch broad `except Exception`, which can surface raw database driver errors, connection details, or internal paths to the client rather than just intentional validation messages. Replace with a fixed, generic message per error class; the existing logger.error(...)/logger.warning(...) calls already capture full detail server-side. In api/routes/ai.py, extract a shared _ai_error_response() helper since the same 3-exception pattern (VectorStoreNotBuilt, ValueError, RuntimeError from get_completion()) repeated verbatim across 4 routes, and add the server-side logging that was missing there entirely. Also fixes an f-string leak in compliance.py's FileNotFoundError handler that the "detail" key search missed. Fixes #177 (CodeQL: information exposure through an exception, all 27 findings across api/app.py and 8 api/routes/ modules). * fix: remove escapeHTML() misapplied to .textContent sinks Self-review caught that the defense-in-depth escapeHTML() calls added for #179 wrapped values assigned via .textContent, not .innerHTML. .textContent never interprets HTML, so escaping there adds no security value while risking visible text corruption (a literal "&" shown on screen) if the underlying value ever contains a special character. toEmbedUrl()'s URL-origin validation is the real, load-bearing fix and is unaffected by this change — it guarantees embedUrl can only ever be '' or a well-formed https://youtube.com|vimeo.com URL regardless of which DOM property ultimately consumes it. * fix(security): resolve Semgrep SAST findings (#185) * fix(security): harden workflow shell execution Route deployment inputs through environment variables and replace remote installer pipes with checksum-verified Syft archives. Consolidate workflow permissions so deployment validation can run. Addresses #182. * fix(security): resolve remaining Semgrep findings Pin workflow and browser dependencies, remove unsafe evaluation and dynamic query construction, enforce trusted network destinations, harden local containers, and prevent sensitive JWT error logging. Fixes #182. * style(security): format endpoint validation * fix(security): preserve validated URL suppression * feat(pqc): add CBOM endpoint, quantum risk scoring, NCSC and ENISA framework mappings, HNDL exposure window and migration roadmap (#187) Signed-off-by: Vishnu Ajith <27vishnu07@gmail.com> * feat(scanner): add enterprise AKS security rule pack (#189) * feat(scanner): add enterprise AKS security rule pack * style(scanner): format AKS rules * ci: document AKS SDK license exception * fix(security): complete #183 XSS and legacy AI key follow-up (#188) Two residual issues from #183's merge, found in post-merge review: - toEmbedUrl() validated the host via new URL() but returned the raw input, so an attribute-injection payload on an allowed host (e.g. https://www.youtube.com/embed/abc" onload="alert(1)) passed validation and kept its literal double-quote, breaking out of the iframe src="..." attribute. Now returns parsed.href, which percent-encodes quotes, spaces, and brackets. - The switch to in-memory key storage removed the localStorage write but never purged keys that older builds had already stored, so existing users kept a plaintext ai_api_key indefinitely. Added a one-time purge on module load (not read into memory) and in clear(). Both fixes ship with regression tests confirmed to fail against the pre-fix code and pass against the fix. Co-authored-by: Claude Fable 5 * docs: add CHANGELOG, API reference, coding standards and OpenSSF gold badge compliance (#190) * docs: add OpenSSF Passing badge (#192) * Add Semgrep SAST to CI alongside CodeQL (#210) * Add Semgrep SAST to CI alongside CodeQL * Add non-root USER to Dockerfile to satisfy Semgrep gate * Document Dockerfile hardening intent and Semgrep registry dependency * Remove issue reference from Dockerfile comment * docs: prepare OpenSSF Silver readiness evidence (#200) * fix(scanner): resolve COR-001-004 scanner correctness issues (#151) (#163) * fix(scanner): resolve COR-001-004 scanner correctness issues (#151) * fix(scanner): normalise Azure SDK enum fields in AZ-NET-003 and AZ-DB-002 Addresses review feedback on PR #163: - Add a shared enum_str() helper in azure_client.py that safely unwraps Azure SDK enum fields via .value, since str(enum_member) yields e.g. 'SecurityRuleDirection.INBOUND' rather than 'Inbound' and silently breaks naive string comparisons against real SDK objects. - AZ-NET-003: normalise direction, access, and source_address_prefix through enum_str() so real SecurityRuleDirection/SecurityRuleAccess enum values are detected correctly, not just plain-string mocks. - AZ-DB-002: normalise the auditing policy state through enum_str() so a real BlobAuditingPolicyState.ENABLED value is not mistaken for disabled (false positive) or vice versa. - AZ-DB-002: malformed ARM IDs are now logged explicitly instead of silently skipped. - AZ-NET-003: the matched plural source_address_prefixes entry is now included in finding metadata. - Add regression tests using real azure-mgmt-network / azure-mgmt-sql SDK model classes (SecurityRule, SecurityRuleDirection, SecurityRuleAccess, ServerBlobAuditingPolicy, BlobAuditingPolicyState) rather than only SimpleNamespace/string-backed mocks, per SHAURYAKSHARMA24's review. - Sync branch with upstream dev (v0.3.0) and apply current ruff format gate, per ritiksah141's review. * fix: remove duplicate _diagnostic_settings init line --------- Co-authored-by: safidnadaf * feat(scanner): add enterprise App Registration and Managed Identity rules (#197) * feat(scanner): add enterprise identity security pack * docs(compliance): use numbered TBD identity placeholders * fix: update parse_resource_id test to match current resource_group behavior * feat(release): attest artifacts and require signed tags (#207) * feat(frontend): add accessibility and i18n foundations (#206) * docs: prepare OpenSSF Silver readiness evidence * feat(frontend): add accessibility and i18n foundations --------- Signed-off-by: Tanvir Farhad * fix: resolve all open security alerts (8 Dependabot + 1 CodeQL) (#222) * fix: resolve all open security alerts (8 Dependabot + 1 CodeQL) Closes #221. Dependency vulnerabilities: - react-router-dom (root and frontend) replaced with react-router 8.3.0. react-router v8 dropped the react-router-dom re-export package, so this is an import migration, not just a version bump: all 9 files that imported from react-router-dom (BrowserRouter, Routes, Route, Navigate, useLocation, useNavigate, NavLink, Outlet) now import from react-router directly, matching v8's actual export surface (react-router/dom only ships RouterProvider/HydratedRouter, which nothing here uses). Fixes Dependabot alerts #12, #10, #8, #7, #6, #5. - postcss bumped to 8.5.18+ (resolved to 8.5.25). Fixes alert #9. - brace-expansion bumped to 5.0.9 via npm audit fix, clearing both the originally reported alert #4 (exponential-time expansion DoS) and a second advisory affecting versions up to and including 5.0.7 (out-of-memory DoS) that the requested 5.0.7 floor would not have cleared on its own. CodeQL alert #31 (py/clear-text-logging-sensitive-data): - scanner/rules/az_idn_006.py logged the raw endDateTime value from a service principal's password credential when it failed to parse. Drops the value from the log line entirely; app_id alone is sufficient to correlate the failure. Matches the fix already proposed in draft PR #220, which this supersedes. - Strengthened the existing regression test to also assert the malformed endDateTime value itself never reaches the logs (it previously only checked keyId), and verified the test fails against the pre-fix code before restoring the fix. Added node_modules/ to the root .gitignore - the root package.json exists only to give Dependabot a manifest to track react-router against, but running npm install there to regenerate its lockfile was leaving an untracked node_modules/ with nothing preventing it from being committed. Verified: npm audit clean (root and frontend, 0 vulnerabilities each), frontend build and lint pass, ruff check/format clean, full pytest suite passes (437 passed, 2 pre-existing failures unrelated to this change - local chromadb version mismatch, not present in CI). Signed-off-by: Tanvir Farhad * style: fix ruff format drift on markdown-embedded Python examples CI's ruff (unpinned) reformatted the embedded code fences in CONTRIBUTING.md, docs/adding-a-rule.md, and docs/architecture.md again since the last fix in b9d4538 - whitespace only, no content changes. Signed-off-by: Tanvir Farhad * fix: declare react-router 8.3.0's runtime requirements per review react-router@8.3.0 requires Node >=22.22.0 and react/react-dom >=19.2.7 (peer deps). Bump the declared React floors, add an engines.node field to frontend/package.json, and pin CI's frontend job to Node 22.22.0 so the requirement is enforced rather than relying on "latest 22.x" happening to be new enough. Addresses ritiksah141's CHANGES_REQUESTED review on PR #222. Signed-off-by: Tanvir Farhad --------- Signed-off-by: Tanvir Farhad --------- Signed-off-by: dependabot[bot] Signed-off-by: Vishnu Ajith <27vishnu07@gmail.com> Signed-off-by: Tanvir Farhad Co-authored-by: Tanvir Farhad Co-authored-by: PARTH J ROHIT Co-authored-by: Ritik Sah Co-authored-by: Shaurya K Sharma Co-authored-by: Shaurya K Sharma Co-authored-by: Mahfuzur Rahman Emon Co-authored-by: Safid Nadaf <137755124+safidnadaf@users.noreply.github.com> Co-authored-by: Abdulbosit Abdurazzakov <2d9c6kh58x@privaterelay.appleid.com> Co-authored-by: Mahfuzur Rahman Emon Co-authored-by: Prayas Gautam <159550781+vogonPrayas@users.noreply.github.com> Co-authored-by: Claude Sonnet 4.6 Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> Co-authored-by: Muhammad Ibrahim <135441675+m-khan-97@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: safidnadaf --- .github/workflows/ci.yml | 5 +- .github/workflows/release.yml | 72 +++++++++++- .github/workflows/sbom-release.yml | 40 ------- .gitignore | 3 + CONTRIBUTING.md | 40 ++++--- README.md | 3 + docs/accessibility-audit.md | 38 +++++++ docs/adding-a-rule.md | 49 +++++---- docs/architecture.md | 26 ++--- docs/ci-pipeline.md | 2 +- docs/internationalization.md | 22 ++++ docs/release-verification.md | 50 +++++++++ frontend/package-lock.json | 104 ++++++++---------- frontend/package.json | 13 ++- frontend/scripts/accessibility-check.mjs | 27 +++++ frontend/src/App.jsx | 13 ++- .../components/compliance/ComplianceTable.jsx | 2 +- frontend/src/components/layout/Header.jsx | 61 +++++----- frontend/src/components/layout/Layout.jsx | 13 ++- frontend/src/components/layout/Sidebar.jsx | 48 ++++---- .../prioritization/QuickRemediation.jsx | 2 +- frontend/src/components/scan/AskAIButton.jsx | 2 +- frontend/src/components/shared/Card.jsx | 13 ++- frontend/src/contexts/I18nContext.jsx | 36 ++++++ frontend/src/i18n/I18nState.js | 9 ++ frontend/src/i18n/messages.js | 41 +++++++ frontend/src/i18n/messages.test.mjs | 11 ++ frontend/src/pages/AILayer.jsx | 2 +- frontend/src/pages/DetailedScan.jsx | 2 +- package-lock.json | 76 +++---------- package.json | 2 +- scanner/rules/az_idn_006.py | 3 +- tests/test_rules_identity.py | 12 +- tests/test_signed_release_workflow.py | 44 ++++++++ 34 files changed, 583 insertions(+), 303 deletions(-) delete mode 100644 .github/workflows/sbom-release.yml create mode 100644 docs/accessibility-audit.md create mode 100644 docs/internationalization.md create mode 100644 docs/release-verification.md create mode 100644 frontend/scripts/accessibility-check.mjs create mode 100644 frontend/src/contexts/I18nContext.jsx create mode 100644 frontend/src/i18n/I18nState.js create mode 100644 frontend/src/i18n/messages.js create mode 100644 frontend/src/i18n/messages.test.mjs create mode 100644 tests/test_signed_release_workflow.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8d47b1c8..9374a646 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -595,7 +595,7 @@ jobs: - name: Set up Node.js uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: - node-version: "22" + node-version: "22.22.0" cache: npm cache-dependency-path: frontend/package-lock.json @@ -608,6 +608,9 @@ jobs: - name: Run aiSettings tests run: node src/utils/aiApi.test.mjs + - name: Run accessibility and internationalization checks + run: npm run test:a11y && npm run test:i18n + - name: Build run: npm run build diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6db3909e..8661e9bc 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,21 +1,85 @@ -name: Release +name: Signed Release on: push: tags: - - 'v*' + - "v*" permissions: contents: write + id-token: write + attestations: write jobs: release: runs-on: ubuntu-latest + env: + TAG: ${{ github.ref_name }} steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + - name: Checkout signed tag + uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 with: fetch-depth: 0 - - uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2 + + - name: Verify annotated tag signature + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + tag_object=$(gh api "repos/${GITHUB_REPOSITORY}/git/ref/tags/${TAG}" --jq '.object.sha') + object_type=$(gh api "repos/${GITHUB_REPOSITORY}/git/ref/tags/${TAG}" --jq '.object.type') + if [ "$object_type" != "tag" ]; then + echo "Release tags must be signed annotated tags; ${TAG} is ${object_type}." + exit 1 + fi + verified=$(gh api "repos/${GITHUB_REPOSITORY}/git/tags/${tag_object}" --jq '.verification.verified') + if [ "$verified" != "true" ]; then + echo "GitHub could not verify the signature on ${TAG}." + exit 1 + fi + + - name: Install Syft + env: + SYFT_VERSION: "1.46.0" + SYFT_SHA256: d654f678b709eb53c393d38519d5ed7d2e57205529404018614cfefa0fb2b5ca + run: | + set -euo pipefail + archive="syft_${SYFT_VERSION}_linux_amd64.tar.gz" + curl --fail --silent --show-error --location \ + --output "$archive" \ + "https://github.com/anchore/syft/releases/download/v${SYFT_VERSION}/${archive}" + echo "${SYFT_SHA256} ${archive}" | sha256sum --check --strict + sudo tar --extract --gzip --file "$archive" --directory /usr/local/bin syft + + - name: Build deterministic release artifacts + run: | + set -euo pipefail + mkdir -p dist + syft dir:. --source-name openshield --source-version "$TAG" \ + -o "cyclonedx-json=dist/openshield-${TAG}-sbom.cyclonedx.json" + git archive --format=tar --prefix="openshield-${TAG}/" "$TAG" | \ + gzip --no-name > "dist/openshield-${TAG}.tar.gz" + cd dist + sha256sum "openshield-${TAG}.tar.gz" "openshield-${TAG}-sbom.cyclonedx.json" > SHA256SUMS + + - name: Attest source archive + uses: actions/attest-build-provenance@0f67c3f4856b2e3261c31976d6725780e5e4c373 # v4.1.1 + with: + subject-path: dist/openshield-${{ env.TAG }}.tar.gz + + - name: Attest SBOM + uses: actions/attest-build-provenance@0f67c3f4856b2e3261c31976d6725780e5e4c373 # v4.1.1 + with: + subject-path: dist/openshield-${{ env.TAG }}-sbom.cyclonedx.json + + - name: Attest checksum manifest + uses: actions/attest-build-provenance@0f67c3f4856b2e3261c31976d6725780e5e4c373 # v4.1.1 + with: + subject-path: dist/SHA256SUMS + + - name: Publish release + uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65 # v2 with: generate_release_notes: true make_latest: true + files: dist/* diff --git a/.github/workflows/sbom-release.yml b/.github/workflows/sbom-release.yml deleted file mode 100644 index 3748dba0..00000000 --- a/.github/workflows/sbom-release.yml +++ /dev/null @@ -1,40 +0,0 @@ -name: SBOM Release - -# Attach a CycloneDX SBOM to each published GitHub Release (issue #156). -on: - release: - types: [published] - -permissions: - contents: write # required to upload assets to the release - -jobs: - attach-sbom: - name: Generate and attach SBOM - runs-on: ubuntu-latest - steps: - - name: Checkout repository - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 - - - name: Install syft - env: - SYFT_VERSION: "1.46.0" - SYFT_SHA256: d654f678b709eb53c393d38519d5ed7d2e57205529404018614cfefa0fb2b5ca - run: | - SYFT_ARCHIVE="syft_${SYFT_VERSION}_linux_amd64.tar.gz" - curl --fail --silent --show-error --location \ - --output "$SYFT_ARCHIVE" \ - "https://github.com/anchore/syft/releases/download/v${SYFT_VERSION}/${SYFT_ARCHIVE}" - echo "${SYFT_SHA256} ${SYFT_ARCHIVE}" | sha256sum --check --strict - sudo tar --extract --gzip --file "$SYFT_ARCHIVE" --directory /usr/local/bin syft - - - name: Generate SBOM - env: - TAG: ${{ github.event.release.tag_name }} - run: syft dir:. --source-name openshield --source-version "$TAG" -o "cyclonedx-json=openshield-${TAG}-sbom.cyclonedx.json" - - - name: Upload SBOM to release - env: - GH_TOKEN: ${{ github.token }} - TAG: ${{ github.event.release.tag_name }} - run: gh release upload "$TAG" "openshield-${TAG}-sbom.cyclonedx.json" --clobber diff --git a/.gitignore b/.gitignore index 87074d69..03a8d80f 100644 --- a/.gitignore +++ b/.gitignore @@ -219,3 +219,6 @@ __marimo__/ ai/vectorstore/ .vercel .env* + +# Node (root package.json exists solely to track react-router for Dependabot) +node_modules/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7c234f46..ebc3e556 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -50,13 +50,9 @@ from typing import Any, Dict, List RULE_ID = "AZ-STOR-001" RULE_NAME = "Public Blob Access Enabled on Storage Account" -SEVERITY = "HIGH" # HIGH / MEDIUM / LOW / INFO -CATEGORY = "Storage" # Storage / Network / Identity / Database / Compute / Key Vault / Kubernetes -FRAMEWORKS = { - "CIS": "3.5", - "NIST": "PR.AC-3", - "ISO27001": "A.9.4.1" -} +SEVERITY = "HIGH" # HIGH / MEDIUM / LOW / INFO +CATEGORY = "Storage" # Storage / Network / Identity / Database / Compute / Key Vault / Kubernetes +FRAMEWORKS = {"CIS": "3.5", "NIST": "PR.AC-3", "ISO27001": "A.9.4.1"} DESCRIPTION = ( "Storage accounts with public blob access enabled allow anyone on the " "internet to read data without authentication. This can lead to data " @@ -72,20 +68,22 @@ def scan(azure_client: Any, subscription_id: str) -> List[Dict[str, Any]]: for account in azure_client.get_storage_accounts(): if getattr(account, "allow_blob_public_access", False): - findings.append({ - "rule_id": RULE_ID, - "rule_name": RULE_NAME, - "severity": SEVERITY, - "category": CATEGORY, - "resource_id": account.id, - "resource_name": account.name, - "resource_type": "Microsoft.Storage/storageAccounts", - "description": DESCRIPTION, - "remediation": REMEDIATION, - "playbook": PLAYBOOK, - "frameworks": FRAMEWORKS, - "metadata": {} - }) + findings.append( + { + "rule_id": RULE_ID, + "rule_name": RULE_NAME, + "severity": SEVERITY, + "category": CATEGORY, + "resource_id": account.id, + "resource_name": account.name, + "resource_type": "Microsoft.Storage/storageAccounts", + "description": DESCRIPTION, + "remediation": REMEDIATION, + "playbook": PLAYBOOK, + "frameworks": FRAMEWORKS, + "metadata": {}, + } + ) return findings ``` diff --git a/README.md b/README.md index 0d9c900e..09ecd71d 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,9 @@ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![CHANGELOG](https://img.shields.io/badge/changelog-here-blue)](CHANGELOG.md) +Release artifacts include SHA-256 checksums, an SBOM, and identity-bound +provenance attestations. See [release verification](docs/release-verification.md). + > **Open source Cloud Security Posture Management (CSPM) for Azure - detect misconfigurations, map to CIS/NIST/ISO27001/SOC2, fix them with one command, and identify cryptographic assets requiring quantum-safe migration.** [![GitHub Repo stars](https://img.shields.io/github/stars/openshield-org/openshield?style=flat-square)](https://github.com/openshield-org/openshield/stargazers) diff --git a/docs/accessibility-audit.md b/docs/accessibility-audit.md new file mode 100644 index 00000000..026cfaab --- /dev/null +++ b/docs/accessibility-audit.md @@ -0,0 +1,38 @@ +# Accessibility Audit + +Assessment date: 16 July 2026. Scope: React dashboard and static project +website. Target: practical alignment with WCAG 2.2 AA; this is not a formal +conformance certification. + +## Controls added + +- A keyboard-visible skip link targets the dashboard's main content. +- Primary navigation and mobile navigation have accessible names. +- Decorative navigation icons are hidden from assistive technology. +- Icon-only close and status actions have accessible labels. +- Popovers and connection errors expose dialog semantics and names. +- Scan results and backend connectivity expose polite live status updates. +- The off-screen mobile navigation is inert while closed. +- A source-level CI check rejects positive tab order, non-semantic clickable + `div`/`span` elements, missing image alternative text, and missing document + language. + +## Keyboard review + +The expected keyboard path is: skip link, mobile menu when present, language +selector, scan control, primary navigation, then page content. Native buttons, +links, inputs and selects retain browser focus behavior. Escape handling remains +available in the scan input. A full screen-reader/browser matrix remains a +release-quality follow-up rather than a claim made by this audit. + +## Known limitations + +- Some data visualizations need separate screen-reader summaries as their + components evolve. +- Focus trapping and restoration for every future modal must be checked during + component review. +- Colour contrast should be rechecked whenever theme tokens change. +- The static website has its own editing surface and needs repeat manual review + when that interface changes. + +Run `npm run test:a11y` from `frontend/` for the automated source checks. diff --git a/docs/adding-a-rule.md b/docs/adding-a-rule.md index e62f43b0..ee12e814 100644 --- a/docs/adding-a-rule.md +++ b/docs/adding-a-rule.md @@ -24,27 +24,26 @@ logger = logging.getLogger(__name__) # ── Required module-level constants ───────────────────────────────────────── -RULE_ID = "AZ-XXXX-000" # Unique ID. Check existing rules to avoid clashes. -RULE_NAME = "Human-readable name" # Shown in the dashboard and reports. -SEVERITY = "HIGH" # HIGH | MEDIUM | LOW | INFO -CATEGORY = "Storage" # Storage | Network | Identity | Database | Compute | Key Vault | Kubernetes +RULE_ID = "AZ-XXXX-000" # Unique ID. Check existing rules to avoid clashes. +RULE_NAME = "Human-readable name" # Shown in the dashboard and reports. +SEVERITY = "HIGH" # HIGH | MEDIUM | LOW | INFO +CATEGORY = "Storage" # Storage | Network | Identity | Database | Compute | Key Vault | Kubernetes FRAMEWORKS = { - "CIS": "3.5", # CIS Azure Benchmark control ID - "NIST": "PR.AC-3", # NIST CSF subcategory - "ISO27001": "A.9.4.1", # ISO 27001 Annex A control + "CIS": "3.5", # CIS Azure Benchmark control ID + "NIST": "PR.AC-3", # NIST CSF subcategory + "ISO27001": "A.9.4.1", # ISO 27001 Annex A control } DESCRIPTION = ( "Explain WHY this is a security risk. One or two sentences. " "What can an attacker do if this misconfiguration exists?" ) -REMEDIATION = ( - "Explain HOW to fix it. What setting to change, or what command to run." -) +REMEDIATION = "Explain HOW to fix it. What setting to change, or what command to run." PLAYBOOK = "playbooks/cli/fix_az_xxxx_000.sh" # path to the matching fix script # ── Required scan function ─────────────────────────────────────────────────── + def scan(azure_client: Any, subscription_id: str) -> List[Dict[str, Any]]: """Return a list of findings. Return [] if no issues are found. @@ -74,20 +73,22 @@ def scan(azure_client: Any, subscription_id: str) -> List[Dict[str, Any]]: continue if status is False: - findings.append({ - "rule_id": RULE_ID, - "rule_name": RULE_NAME, - "severity": SEVERITY, - "category": CATEGORY, - "resource_id": resource_id, - "resource_name": resource_name, - "resource_type": "Microsoft.Storage/storageAccounts", # ← update - "description": DESCRIPTION, - "remediation": REMEDIATION, - "playbook": PLAYBOOK, - "frameworks": FRAMEWORKS, - "metadata": {}, - }) + findings.append( + { + "rule_id": RULE_ID, + "rule_name": RULE_NAME, + "severity": SEVERITY, + "category": CATEGORY, + "resource_id": resource_id, + "resource_name": resource_name, + "resource_type": "Microsoft.Storage/storageAccounts", # ← update + "description": DESCRIPTION, + "remediation": REMEDIATION, + "playbook": PLAYBOOK, + "frameworks": FRAMEWORKS, + "metadata": {}, + } + ) return findings ``` diff --git a/docs/architecture.md b/docs/architecture.md index 2249851f..317bc7e5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -131,20 +131,20 @@ Every finding returned by a rule must conform to this schema: ```python { - "rule_id": str, # e.g. "AZ-STOR-001" - "rule_name": str, - "severity": str, # HIGH | MEDIUM | LOW | INFO - "category": str, # Storage | Network | Identity | Database | Compute | Key Vault - "resource_id": str, # full Azure resource ID + "rule_id": str, # e.g. "AZ-STOR-001" + "rule_name": str, + "severity": str, # HIGH | MEDIUM | LOW | INFO + "category": str, # Storage | Network | Identity | Database | Compute | Key Vault + "resource_id": str, # full Azure resource ID "resource_name": str, - "resource_type": str, # e.g. "Microsoft.Storage/storageAccounts" - "description": str, - "remediation": str, - "playbook": str, # path to the CLI remediation script - "frameworks": dict, # {"CIS": "3.5", "NIST": "PR.AC-3", "ISO27001": "A.9.4.1"} - "metadata": dict, # optional rule-specific context - "detected_at": str, # ISO 8601, added by engine - "scan_id": str, # UUID, added by engine + "resource_type": str, # e.g. "Microsoft.Storage/storageAccounts" + "description": str, + "remediation": str, + "playbook": str, # path to the CLI remediation script + "frameworks": dict, # {"CIS": "3.5", "NIST": "PR.AC-3", "ISO27001": "A.9.4.1"} + "metadata": dict, # optional rule-specific context + "detected_at": str, # ISO 8601, added by engine + "scan_id": str, # UUID, added by engine } ``` diff --git a/docs/ci-pipeline.md b/docs/ci-pipeline.md index 0b5c015b..a0047a1c 100644 --- a/docs/ci-pipeline.md +++ b/docs/ci-pipeline.md @@ -27,7 +27,7 @@ This document explains each job, how to reproduce every check locally before ope `.github/workflows/codeql.yml` (separate workflow, PRs to `dev`/`main` + weekly cron): **Analyze (python)** and **Analyze (javascript)** — CodeQL semantic/taint analysis. -`.github/workflows/sbom-release.yml` (triggered `on: release: published`): generates a CycloneDX SBOM from the tagged code and uploads it to the GitHub Release assets. +`.github/workflows/release.yml` (triggered by `v*` tags): requires a verified signed annotated tag, builds a deterministic source archive and CycloneDX SBOM, publishes SHA-256 checksums and identity-bound provenance attestations, then creates the GitHub Release. The **Container Scan** job is intentionally **not** a required check yet: no `Dockerfile` exists, so it has nothing to scan. It activates automatically once INFRA 1 (#154) adds one. diff --git a/docs/internationalization.md b/docs/internationalization.md new file mode 100644 index 00000000..f8480831 --- /dev/null +++ b/docs/internationalization.md @@ -0,0 +1,22 @@ +# Internationalization + +The dashboard uses message catalogs through `I18nContext`. English is the +fallback language and Spanish demonstrates a second complete catalog for core +navigation, page titles, scan controls, status messages and theme controls. + +The selected locale is stored locally, applied to the document `lang` +attribute, and used with `Intl.DateTimeFormat` and `Intl.NumberFormat`. An +unsupported locale falls back to English. Security identifiers, Azure resource +names, findings and compliance control IDs are data and are never translated. + +## Adding a locale + +1. Add a catalog to `frontend/src/i18n/messages.js` using exactly the English + keys. +2. Translate meaning rather than word order; retain `{name}` placeholders. +3. Add the language's self-name to each catalog. +4. Run `npm run test:i18n`; missing keys fail the catalog test. +5. Review navigation at narrow and wide widths and verify date/number output. + +The website remains English-first. Additional website locales should reuse the +same terminology but must not duplicate security data or rule definitions. diff --git a/docs/release-verification.md b/docs/release-verification.md new file mode 100644 index 00000000..d1244df3 --- /dev/null +++ b/docs/release-verification.md @@ -0,0 +1,50 @@ +# Verifying OpenShield Releases + +OpenShield release artifacts are produced only from a GitHub-verified signed +annotated tag. GitHub Actions generates a deterministic source archive, a +CycloneDX SBOM and SHA-256 checksums, then creates identity-bound Sigstore +provenance attestations before uploading the files to the release. + +## Verify checksums + +Download all release assets into one directory, then run: + +```bash +sha256sum --check SHA256SUMS +``` + +## Verify provenance + +Install the GitHub CLI and verify each artifact against this repository: + +```bash +gh attestation verify openshield-vX.Y.Z.tar.gz \ + --repo openshield-org/openshield \ + --signer-workflow openshield-org/openshield/.github/workflows/release.yml + +gh attestation verify openshield-vX.Y.Z-sbom.cyclonedx.json \ + --repo openshield-org/openshield \ + --signer-workflow openshield-org/openshield/.github/workflows/release.yml + +gh attestation verify SHA256SUMS \ + --repo openshield-org/openshield \ + --signer-workflow openshield-org/openshield/.github/workflows/release.yml +``` + +Successful verification proves that the artifact digest was attested by the +OpenShield release workflow for this public repository. It does not mean that +GitHub or Sigstore audited the source code. + +## Maintainer release procedure + +1. Confirm the release commit is on the approved `main` history and CI passes. +2. Create a signed annotated tag: `git tag -s vX.Y.Z -m "OpenShield vX.Y.Z"`. + SSH signing may be used when Git is configured with `gpg.format=ssh`. +3. Verify locally with `git tag -v vX.Y.Z` using the project's trusted signer + configuration. +4. Push only the tag: `git push origin vX.Y.Z`. +5. The workflow independently asks GitHub to verify the tag signature. A + lightweight or unverified tag fails before artifacts are produced. +6. After publication, download and verify every asset using the commands above. + +Existing historical lightweight tags are not retroactively described as signed. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index cab1e076..b96d8954 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -9,11 +9,11 @@ "version": "0.0.0", "dependencies": { "autoprefixer": "^10.5.0", - "postcss": "^8.5.15", - "react": "^19.2.6", - "react-dom": "^19.2.6", + "postcss": "^8.5.18", + "react": "^19.2.7", + "react-dom": "^19.2.7", "react-icons": "^5.6.0", - "react-router-dom": "^7.16.0", + "react-router": "^8.3.0", "recharts": "^3.8.1" }, "devDependencies": { @@ -27,6 +27,9 @@ "globals": "^17.6.0", "tailwindcss": "^3.4.19", "vite": "^8.0.16" + }, + "engines": { + "node": ">=22.22.0" } }, "node_modules/@alloc/quick-lru": { @@ -1186,15 +1189,16 @@ } }, "node_modules/brace-expansion": { - "version": "5.0.6", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz", - "integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==", + "version": "5.0.9", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz", + "integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==", "dev": true, + "license": "MIT", "dependencies": { "balanced-match": "^4.0.2" }, "engines": { - "node": "18 || 20 || >=22" + "node": "20 || >=22" } }, "node_modules/braces": { @@ -1328,17 +1332,11 @@ "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", "dev": true }, - "node_modules/cookie": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", - "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } + "node_modules/cookie-es": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/cookie-es/-/cookie-es-3.1.1.tgz", + "integrity": "sha512-UaXxwISYJPTr9hwQxMFYZ7kNhSXboMXP+Z3TRX6f1/NyaGPfuNUZOWP1pUEb75B2HjfklIYLVRfWiFZJyC6Npg==", + "license": "MIT" }, "node_modules/cross-spawn": { "version": "7.0.6", @@ -2512,15 +2510,16 @@ } }, "node_modules/nanoid": { - "version": "3.3.12", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz", - "integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==", + "version": "3.3.16", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.16.tgz", + "integrity": "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==", "funding": [ { "type": "github", "url": "https://github.com/sponsors/ai" } ], + "license": "MIT", "bin": { "nanoid": "bin/nanoid.cjs" }, @@ -2676,9 +2675,9 @@ } }, "node_modules/postcss": { - "version": "8.5.15", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz", - "integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==", + "version": "8.5.25", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.25.tgz", + "integrity": "sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw==", "funding": [ { "type": "opencollective", @@ -2693,8 +2692,9 @@ "url": "https://github.com/sponsors/ai" } ], + "license": "MIT", "dependencies": { - "nanoid": "^3.3.12", + "nanoid": "^3.3.16", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" }, @@ -2868,22 +2868,24 @@ ] }, "node_modules/react": { - "version": "19.2.6", - "resolved": "https://registry.npmjs.org/react/-/react-19.2.6.tgz", - "integrity": "sha512-sfWGGfavi0xr8Pg0sVsyHMAOziVYKgPLNrS7ig+ivMNb3wbCBw3KxtflsGBAwD3gYQlE/AEZsTLgToRrSCjb0Q==", + "version": "19.2.8", + "resolved": "https://registry.npmjs.org/react/-/react-19.2.8.tgz", + "integrity": "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==", + "license": "MIT", "engines": { "node": ">=0.10.0" } }, "node_modules/react-dom": { - "version": "19.2.6", - "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.6.tgz", - "integrity": "sha512-0prMI+hvBbPjsWnxDLxlCGyM8PN6UuWjEUCYmZhO67xIV9Xasa/r/vDnq+Xyq4Lo27g8QSbO5YzARu0D1Sps3g==", + "version": "19.2.8", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.8.tgz", + "integrity": "sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ==", + "license": "MIT", "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { - "react": "^19.2.6" + "react": "^19.2.8" } }, "node_modules/react-icons": { @@ -2923,19 +2925,19 @@ } }, "node_modules/react-router": { - "version": "7.16.0", - "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.16.0.tgz", - "integrity": "sha512-wArC8lVyJb3+jM9OpDyW6hLCizACWkvQR/sSGqSs+o5uEXEtGlqdZ4v8hENR3Jad6i+LRkK93q/+bQAcvl6V1A==", + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-8.3.0.tgz", + "integrity": "sha512-qyPMvW83jGIct3yiieisxdk9M745anqhpIMKN5m1t6yBMfgVPpt77aHOqs5fUlEJRMCGffg9BaQLH9oPVOL7xQ==", + "license": "MIT", "dependencies": { - "cookie": "^1.0.1", - "set-cookie-parser": "^2.6.0" + "cookie-es": "^3.1.1" }, "engines": { - "node": ">=20.0.0" + "node": ">=22.22.0" }, "peerDependencies": { - "react": ">=18", - "react-dom": ">=18" + "react": ">=19.2.7", + "react-dom": ">=19.2.7" }, "peerDependenciesMeta": { "react-dom": { @@ -2943,21 +2945,6 @@ } } }, - "node_modules/react-router-dom": { - "version": "7.16.0", - "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.16.0.tgz", - "integrity": "sha512-kMUAbimWB5FVbF4Bce4bJsiKJWLIUHq/mEG8+CFDnCSgltptBiG5nguducmsJeGKytlCvQud9Qhzpn49iduTlA==", - "dependencies": { - "react-router": "7.16.0" - }, - "engines": { - "node": ">=20.0.0" - }, - "peerDependencies": { - "react": ">=18", - "react-dom": ">=18" - } - }, "node_modules/read-cache": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz", @@ -3140,11 +3127,6 @@ "semver": "bin/semver.js" } }, - "node_modules/set-cookie-parser": { - "version": "2.7.2", - "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz", - "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==" - }, "node_modules/shebang-command": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", diff --git a/frontend/package.json b/frontend/package.json index 631146ac..87822b65 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -3,19 +3,24 @@ "private": true, "version": "0.0.0", "type": "module", + "engines": { + "node": ">=22.22.0" + }, "scripts": { "dev": "vite", "build": "vite build", "lint": "eslint . --max-warnings=0", + "test:i18n": "node src/i18n/messages.test.mjs", + "test:a11y": "node scripts/accessibility-check.mjs", "preview": "vite preview" }, "dependencies": { "autoprefixer": "^10.5.0", - "postcss": "^8.5.15", - "react": "^19.2.6", - "react-dom": "^19.2.6", + "postcss": "^8.5.18", + "react": "^19.2.7", + "react-dom": "^19.2.7", "react-icons": "^5.6.0", - "react-router-dom": "^7.16.0", + "react-router": "^8.3.0", "recharts": "^3.8.1" }, "devDependencies": { diff --git a/frontend/scripts/accessibility-check.mjs b/frontend/scripts/accessibility-check.mjs new file mode 100644 index 00000000..35f8150f --- /dev/null +++ b/frontend/scripts/accessibility-check.mjs @@ -0,0 +1,27 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; + +const root = path.resolve(import.meta.dirname, '..'); +const sourceRoot = path.join(root, 'src'); + +function filesUnder(directory) { + return fs.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { + const full = path.join(directory, entry.name); + return entry.isDirectory() ? filesUnder(full) : [full]; + }); +} + +const html = fs.readFileSync(path.join(root, 'index.html'), 'utf8'); +assert.match(html, /]+lang="[a-z]{2}"/i, 'frontend HTML must declare a language'); + +for (const file of filesUnder(sourceRoot).filter((item) => /\.(jsx?|html)$/.test(item))) { + const source = fs.readFileSync(file, 'utf8'); + assert.doesNotMatch(source, /tabIndex=["'{]?[1-9]/, `${file} uses a positive tab order`); + assert.doesNotMatch(source, /<(div|span)\b[^>]*\bonClick=/, `${file} uses a non-semantic clickable element`); + for (const image of source.matchAll(/]*>/g)) { + assert.match(image[0], /\balt=/, `${file} contains an image without alt text`); + } +} + +console.log('accessibility static checks passed'); diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 206e84f5..0964a2ca 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -1,6 +1,7 @@ import { useEffect } from 'react'; -import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'; +import { BrowserRouter, Routes, Route, Navigate } from 'react-router'; import { DarkModeProvider } from './contexts/DarkModeContext'; +import { I18nProvider } from './contexts/I18nContext'; import { api } from './utils/api'; import Layout from './components/layout/Layout'; import Discovery from './pages/Discovery'; @@ -25,8 +26,9 @@ export default function App() { return ( - - + + + }> } /> } /> @@ -37,8 +39,9 @@ export default function App() { } /> } /> - - + + + ); } diff --git a/frontend/src/components/compliance/ComplianceTable.jsx b/frontend/src/components/compliance/ComplianceTable.jsx index f1d18e0e..dc04f647 100644 --- a/frontend/src/components/compliance/ComplianceTable.jsx +++ b/frontend/src/components/compliance/ComplianceTable.jsx @@ -1,4 +1,4 @@ -import { useNavigate } from 'react-router-dom'; +import { useNavigate } from 'react-router'; import { FiCheckCircle, FiXCircle, FiMinusCircle, FiArrowRight } from 'react-icons/fi'; import SeverityBadge from '../shared/SeverityBadge'; diff --git a/frontend/src/components/layout/Header.jsx b/frontend/src/components/layout/Header.jsx index feb635f2..53c41f05 100644 --- a/frontend/src/components/layout/Header.jsx +++ b/frontend/src/components/layout/Header.jsx @@ -1,27 +1,23 @@ import { useEffect, useRef, useState } from 'react'; -import { useLocation } from 'react-router-dom'; +import { useLocation } from 'react-router'; import { FiMenu, FiAlertTriangle, FiX, FiLoader, FiZap, FiCheckCircle, FiAlertCircle, FiClock, } from 'react-icons/fi'; import { api } from '../../utils/api'; +import { useI18n } from '../../i18n/I18nState'; -const PAGE_TITLES = { - '/monitoring': { title: 'Security Monitoring', subtitle: 'Overall health score and trends' }, - '/discovery': { title: 'Resource Discovery', subtitle: 'All resources across your Azure environment' }, - '/prioritization': { title: 'Risk Prioritization', subtitle: 'What to fix first based on risk and effort' }, - '/scan': { title: 'Detailed Scan', subtitle: 'Findings with step-by-step remediation playbooks' }, - '/compliance': { title: 'Compliance', subtitle: 'Framework tracking and control status' }, - '/drift': { title: 'Configuration Drift', subtitle: 'Detect unexpected changes to your environment' }, - '/ai': { title: 'AI Assistant', subtitle: 'Ask questions about your security posture' }, +const PAGE_KEYS = { + '/monitoring': 'monitoring', '/discovery': 'discovery', '/prioritization': 'prioritization', + '/scan': 'scan', '/compliance': 'compliance', '/drift': 'drift', '/ai': 'ai', }; // ── Connection-error popup ───────────────────────────────────────────────── function ConnectionErrorPopup({ apiBase, onClose }) { return ( <> -
-
+
@@ -68,7 +64,7 @@ function ScanToast({ result, error, onClose }) { const isSuccess = !!result; return ( -
+
-
@@ -126,10 +122,10 @@ function ScanInputPopover({ onConfirm, onCancel }) { return ( <> -
-
+ @@ -268,6 +268,15 @@ export default function Header({ onMenuToggle }) { {/* Right: controls */}
+ + {/* Run Scan button + popover wrapper */}
@@ -282,7 +291,7 @@ export default function Header({ onMenuToggle }) { : } - {scanning ? `Scanning… ${elapsed}s` : 'Run Scan'} + {scanning ? t('scan.scanning', { seconds: elapsed }) : t('scan.run')} @@ -298,12 +307,14 @@ export default function Header({ onMenuToggle }) { {lastScanAt && isLive && (
- Last scanned: {lastScanAt} + {t('scan.last', { date: lastScanAt })}
)} {/* Live / Reconnecting status dot */}
@@ -316,7 +327,7 @@ export default function Header({ onMenuToggle }) { )} - {isLive ? 'Live' : 'Reconnecting'} + {isLive ? t('status.live') : t('status.reconnecting')}
diff --git a/frontend/src/components/layout/Layout.jsx b/frontend/src/components/layout/Layout.jsx index 01a23c40..fc1d99aa 100644 --- a/frontend/src/components/layout/Layout.jsx +++ b/frontend/src/components/layout/Layout.jsx @@ -1,16 +1,23 @@ import { useState } from 'react'; -import { Outlet } from 'react-router-dom'; +import { Outlet } from 'react-router'; import Sidebar from './Sidebar'; import Header from './Header'; +import { useI18n } from '../../i18n/I18nState'; export default function Layout() { const [sidebarOpen, setSidebarOpen] = useState(false); + const { t } = useI18n(); return (
+ + {t('skip.content')} + {/* Mobile overlay */} {sidebarOpen && ( -
setSidebarOpen(false)} /> @@ -20,7 +27,7 @@ export default function Layout() {
setSidebarOpen((v) => !v)} /> -
+
diff --git a/frontend/src/components/layout/Sidebar.jsx b/frontend/src/components/layout/Sidebar.jsx index e79074ab..f11e1acf 100644 --- a/frontend/src/components/layout/Sidebar.jsx +++ b/frontend/src/components/layout/Sidebar.jsx @@ -1,34 +1,36 @@ -import { NavLink } from 'react-router-dom'; +import { NavLink } from 'react-router'; import { FiActivity, FiSearch, FiTarget, FiZap, FiShield, FiGitBranch, FiCpu, FiSun, FiMoon, FiX, } from 'react-icons/fi'; import { useDarkMode } from '../../contexts/DarkModeContext'; +import { useI18n } from '../../i18n/I18nState'; import Logo from '../shared/Logo'; const navItems = [ - { path: '/monitoring', label: 'Monitor', Icon: FiActivity }, - { path: '/discovery', label: 'Discover', Icon: FiSearch }, - { path: '/prioritization', label: 'Prioritize', Icon: FiTarget }, - { path: '/scan', label: 'Scan', Icon: FiZap }, - { path: '/compliance', label: 'Comply', Icon: FiShield }, - { path: '/drift', label: 'Drift', Icon: FiGitBranch }, - { path: '/ai', label: 'AI', Icon: FiCpu }, + { path: '/monitoring', key: 'monitoring', Icon: FiActivity }, + { path: '/discovery', key: 'discovery', Icon: FiSearch }, + { path: '/prioritization', key: 'prioritization', Icon: FiTarget }, + { path: '/scan', key: 'scan', Icon: FiZap }, + { path: '/compliance', key: 'compliance', Icon: FiShield }, + { path: '/drift', key: 'drift', Icon: FiGitBranch }, + { path: '/ai', key: 'ai', Icon: FiCpu }, ]; export default function Sidebar({ isOpen, onClose }) { const { isDark, toggle } = useDarkMode(); + const { t } = useI18n(); return ( <> {/* ── Desktop sidebar (always visible on lg+) ── */} -
{/* Drawer nav */} -
diff --git a/frontend/src/components/prioritization/QuickRemediation.jsx b/frontend/src/components/prioritization/QuickRemediation.jsx index c4e5ab43..813c44cb 100644 --- a/frontend/src/components/prioritization/QuickRemediation.jsx +++ b/frontend/src/components/prioritization/QuickRemediation.jsx @@ -1,6 +1,6 @@ import { useEffect, useState } from 'react'; import { FiLayout, FiTerminal, FiClock, FiArrowRight, FiTool, FiAlertTriangle } from 'react-icons/fi'; -import { useNavigate } from 'react-router-dom'; +import { useNavigate } from 'react-router'; const EFFORT_ETA = { 1: '15–30 mins', 2: '1–2 hours', 3: '2–4 hours', 4: '~1 day', 5: '2–3 days' }; diff --git a/frontend/src/components/scan/AskAIButton.jsx b/frontend/src/components/scan/AskAIButton.jsx index fbd89889..8102c950 100644 --- a/frontend/src/components/scan/AskAIButton.jsx +++ b/frontend/src/components/scan/AskAIButton.jsx @@ -1,5 +1,5 @@ import { FiCpu } from 'react-icons/fi'; -import { useNavigate } from 'react-router-dom'; +import { useNavigate } from 'react-router'; export default function AskAIButton({ finding }) { const navigate = useNavigate(); diff --git a/frontend/src/components/shared/Card.jsx b/frontend/src/components/shared/Card.jsx index bafe013b..363fb708 100644 --- a/frontend/src/components/shared/Card.jsx +++ b/frontend/src/components/shared/Card.jsx @@ -1,10 +1,15 @@ export default function Card({ children, className = '', onClick }) { + const classes = `rounded-2xl border border-border-light dark:border-border-dark bg-bg-primary dark:bg-bg-dark-secondary p-6 shadow-soft hover:shadow-soft-lg transition-all duration-200 ${onClick ? 'cursor-pointer' : ''} ${className}`; + if (onClick) { + return ( + + ); + } return ( -
+
{children}
); diff --git a/frontend/src/contexts/I18nContext.jsx b/frontend/src/contexts/I18nContext.jsx new file mode 100644 index 00000000..f56e34f0 --- /dev/null +++ b/frontend/src/contexts/I18nContext.jsx @@ -0,0 +1,36 @@ +import { useEffect, useMemo, useState } from 'react'; +import { DEFAULT_LOCALE, messages, translate } from '../i18n/messages'; +import { I18nState } from '../i18n/I18nState'; +const STORAGE_KEY = 'openshield.locale'; + +function initialLocale() { + const stored = window.localStorage.getItem(STORAGE_KEY); + if (stored && messages[stored]) return stored; + const browserLocale = window.navigator.language?.split('-')[0]; + return messages[browserLocale] ? browserLocale : DEFAULT_LOCALE; +} + +export function I18nProvider({ children }) { + const [locale, setLocaleState] = useState(initialLocale); + + const setLocale = (nextLocale) => { + const supported = messages[nextLocale] ? nextLocale : DEFAULT_LOCALE; + window.localStorage.setItem(STORAGE_KEY, supported); + setLocaleState(supported); + }; + + useEffect(() => { + document.documentElement.lang = locale; + }, [locale]); + + const value = useMemo(() => ({ + locale, + locales: Object.keys(messages), + setLocale, + t: (key, values) => translate(locale, key, values), + formatDate: (value, options) => new Intl.DateTimeFormat(locale, options).format(new Date(value)), + formatNumber: (value, options) => new Intl.NumberFormat(locale, options).format(value), + }), [locale]); + + return {children}; +} diff --git a/frontend/src/i18n/I18nState.js b/frontend/src/i18n/I18nState.js new file mode 100644 index 00000000..5a4283fd --- /dev/null +++ b/frontend/src/i18n/I18nState.js @@ -0,0 +1,9 @@ +import { createContext, useContext } from 'react'; + +export const I18nState = createContext(null); + +export function useI18n() { + const context = useContext(I18nState); + if (!context) throw new Error('useI18n must be used inside I18nProvider'); + return context; +} diff --git a/frontend/src/i18n/messages.js b/frontend/src/i18n/messages.js new file mode 100644 index 00000000..dfe1ebe4 --- /dev/null +++ b/frontend/src/i18n/messages.js @@ -0,0 +1,41 @@ +export const DEFAULT_LOCALE = 'en'; + +export const messages = { + en: { + 'nav.monitoring': 'Monitor', 'nav.discovery': 'Discover', 'nav.prioritization': 'Prioritize', + 'nav.scan': 'Scan', 'nav.compliance': 'Comply', 'nav.drift': 'Drift', 'nav.ai': 'AI', + 'theme.dark': 'Dark mode', 'theme.light': 'Light mode', 'theme.toggle': 'Toggle colour theme', + 'menu.open': 'Open menu', 'menu.close': 'Close menu', 'nav.primary': 'Primary navigation', + 'language.label': 'Language', 'language.en': 'English', 'language.es': 'Español', + 'page.monitoring.title': 'Security Monitoring', 'page.monitoring.subtitle': 'Overall health score and trends', + 'page.discovery.title': 'Resource Discovery', 'page.discovery.subtitle': 'All resources across your Azure environment', + 'page.prioritization.title': 'Risk Prioritization', 'page.prioritization.subtitle': 'What to fix first based on risk and effort', + 'page.scan.title': 'Detailed Scan', 'page.scan.subtitle': 'Findings with step-by-step remediation playbooks', + 'page.compliance.title': 'Compliance', 'page.compliance.subtitle': 'Framework tracking and control status', + 'page.drift.title': 'Configuration Drift', 'page.drift.subtitle': 'Detect unexpected changes to your environment', + 'page.ai.title': 'AI Assistant', 'page.ai.subtitle': 'Ask questions about your security posture', + 'scan.run': 'Run Scan', 'scan.scanning': 'Scanning… {seconds}s', 'scan.last': 'Last scanned: {date}', + 'status.live': 'Live', 'status.reconnecting': 'Reconnecting', 'skip.content': 'Skip to main content', + }, + es: { + 'nav.monitoring': 'Monitorear', 'nav.discovery': 'Descubrir', 'nav.prioritization': 'Priorizar', + 'nav.scan': 'Escanear', 'nav.compliance': 'Cumplimiento', 'nav.drift': 'Cambios', 'nav.ai': 'IA', + 'theme.dark': 'Modo oscuro', 'theme.light': 'Modo claro', 'theme.toggle': 'Cambiar tema de color', + 'menu.open': 'Abrir menú', 'menu.close': 'Cerrar menú', 'nav.primary': 'Navegación principal', + 'language.label': 'Idioma', 'language.en': 'English', 'language.es': 'Español', + 'page.monitoring.title': 'Monitoreo de seguridad', 'page.monitoring.subtitle': 'Puntuación general y tendencias', + 'page.discovery.title': 'Descubrimiento de recursos', 'page.discovery.subtitle': 'Recursos del entorno de Azure', + 'page.prioritization.title': 'Priorización de riesgos', 'page.prioritization.subtitle': 'Qué corregir primero según riesgo y esfuerzo', + 'page.scan.title': 'Escaneo detallado', 'page.scan.subtitle': 'Hallazgos y guías de corrección', + 'page.compliance.title': 'Cumplimiento', 'page.compliance.subtitle': 'Controles y marcos de cumplimiento', + 'page.drift.title': 'Cambios de configuración', 'page.drift.subtitle': 'Cambios inesperados del entorno', + 'page.ai.title': 'Asistente de IA', 'page.ai.subtitle': 'Preguntas sobre la postura de seguridad', + 'scan.run': 'Ejecutar escaneo', 'scan.scanning': 'Escaneando… {seconds}s', 'scan.last': 'Último escaneo: {date}', + 'status.live': 'En línea', 'status.reconnecting': 'Reconectando', 'skip.content': 'Saltar al contenido principal', + }, +}; + +export function translate(locale, key, values = {}) { + const template = messages[locale]?.[key] ?? messages[DEFAULT_LOCALE][key] ?? key; + return Object.entries(values).reduce((text, [name, value]) => text.replaceAll(`{${name}}`, String(value)), template); +} diff --git a/frontend/src/i18n/messages.test.mjs b/frontend/src/i18n/messages.test.mjs new file mode 100644 index 00000000..5d090335 --- /dev/null +++ b/frontend/src/i18n/messages.test.mjs @@ -0,0 +1,11 @@ +import assert from 'node:assert/strict'; +import { DEFAULT_LOCALE, messages, translate } from './messages.js'; + +const referenceKeys = Object.keys(messages[DEFAULT_LOCALE]).sort(); +for (const [locale, catalog] of Object.entries(messages)) { + assert.deepEqual(Object.keys(catalog).sort(), referenceKeys, `${locale} must contain the complete message catalog`); +} +assert.equal(translate('es', 'nav.monitoring'), 'Monitorear'); +assert.equal(translate('unknown', 'nav.monitoring'), 'Monitor'); +assert.equal(translate('en', 'scan.scanning', { seconds: 12 }), 'Scanning… 12s'); +console.log('i18n catalogs valid'); diff --git a/frontend/src/pages/AILayer.jsx b/frontend/src/pages/AILayer.jsx index ed378406..6efa514d 100644 --- a/frontend/src/pages/AILayer.jsx +++ b/frontend/src/pages/AILayer.jsx @@ -1,5 +1,5 @@ import { useEffect, useRef, useState } from 'react'; -import { useLocation } from 'react-router-dom'; +import { useLocation } from 'react-router'; import { FiCpu, FiX, FiAlertCircle, FiKey, FiCheckCircle } from 'react-icons/fi'; import { api } from '../utils/api'; import { aiApi, aiSettings } from '../utils/aiApi'; diff --git a/frontend/src/pages/DetailedScan.jsx b/frontend/src/pages/DetailedScan.jsx index 41c8fee0..a84c43fb 100644 --- a/frontend/src/pages/DetailedScan.jsx +++ b/frontend/src/pages/DetailedScan.jsx @@ -1,5 +1,5 @@ import { useEffect, useState } from 'react'; -import { useLocation, useNavigate } from 'react-router-dom'; +import { useLocation, useNavigate } from 'react-router'; import { FiArrowLeft, FiX, FiAlertTriangle } from 'react-icons/fi'; import { api } from '../utils/api'; import FindingHeader from '../components/scan/FindingHeader'; diff --git a/package-lock.json b/package-lock.json index 3185cd89..c309db65 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5,21 +5,14 @@ "packages": { "": { "dependencies": { - "react-router-dom": "^7.18.0" + "react-router": "^8.3.0" } }, - "node_modules/cookie": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz", - "integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==", - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } + "node_modules/cookie-es": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/cookie-es/-/cookie-es-3.1.1.tgz", + "integrity": "sha512-UaXxwISYJPTr9hwQxMFYZ7kNhSXboMXP+Z3TRX6f1/NyaGPfuNUZOWP1pUEb75B2HjfklIYLVRfWiFZJyC6Npg==", + "license": "MIT" }, "node_modules/react": { "version": "19.2.7", @@ -31,69 +24,26 @@ "node": ">=0.10.0" } }, - "node_modules/react-dom": { - "version": "19.2.7", - "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.7.tgz", - "integrity": "sha512-t0BRVXvbiE/o20Hfw669rLbMCDWtYZLvmJigy2f0MxsXF+71pxhR3xOkspmsO8h3ZlNzyibAmtCa3l4lYKk6gQ==", - "license": "MIT", - "peer": true, - "dependencies": { - "scheduler": "^0.27.0" - }, - "peerDependencies": { - "react": "^19.2.7" - } - }, "node_modules/react-router": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.0.tgz", - "integrity": "sha512-pTTGt8J+ji1NOmYnjzT+bAJy/1zD+Jp4ziO6cL7T3ZLvXKtusO7BpFqlRXitqpcPVqllsIXFHRMt+2/k3Xn6HQ==", + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-8.3.0.tgz", + "integrity": "sha512-qyPMvW83jGIct3yiieisxdk9M745anqhpIMKN5m1t6yBMfgVPpt77aHOqs5fUlEJRMCGffg9BaQLH9oPVOL7xQ==", "license": "MIT", "dependencies": { - "cookie": "^1.0.1", - "set-cookie-parser": "^2.6.0" + "cookie-es": "^3.1.1" }, "engines": { - "node": ">=20.0.0" + "node": ">=22.22.0" }, "peerDependencies": { - "react": ">=18", - "react-dom": ">=18" + "react": ">=19.2.7", + "react-dom": ">=19.2.7" }, "peerDependenciesMeta": { "react-dom": { "optional": true } } - }, - "node_modules/react-router-dom": { - "version": "7.18.0", - "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.0.tgz", - "integrity": "sha512-Fi0yY6kgtKae/Th2xibdWK0KSdYZ4B53Gyf6wRtomOKWgpNm7H7+DyfDhncdz9FKbpS+1jmDhg3F4WoGJ+yFOA==", - "license": "MIT", - "dependencies": { - "react-router": "7.18.0" - }, - "engines": { - "node": ">=20.0.0" - }, - "peerDependencies": { - "react": ">=18", - "react-dom": ">=18" - } - }, - "node_modules/scheduler": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", - "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", - "license": "MIT", - "peer": true - }, - "node_modules/set-cookie-parser": { - "version": "2.7.2", - "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz", - "integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==", - "license": "MIT" } } } diff --git a/package.json b/package.json index ab50d954..aab11f60 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { "dependencies": { - "react-router-dom": "^7.18.0" + "react-router": "^8.3.0" } } diff --git a/scanner/rules/az_idn_006.py b/scanner/rules/az_idn_006.py index ebffe970..231f3574 100644 --- a/scanner/rules/az_idn_006.py +++ b/scanner/rules/az_idn_006.py @@ -71,9 +71,8 @@ def scan(azure_client: Any, subscription_id: str) -> List[Dict[str, Any]]: already_expired = end_dt < now except ValueError: logger.debug( - "AZ-IDN-006: Invalid endDateTime for app_id=%s: %r", + "AZ-IDN-006: Invalid endDateTime format for app_id=%s", app_id, - end_dt_str, ) if not (age_days >= EXPIRY_THRESHOLD_DAYS or no_expiry or already_expired): diff --git a/tests/test_rules_identity.py b/tests/test_rules_identity.py index b2ea214e..3c88f83d 100644 --- a/tests/test_rules_identity.py +++ b/tests/test_rules_identity.py @@ -289,11 +289,12 @@ def test_idn_006_noncompliant_secret_no_expiry_returns_finding(mock_azure, subsc def test_idn_006_malformed_end_date_time_does_not_log_key_id(mock_azure, subscription_id, monkeypatch, caplog): - """CodeQL: clear-text logging of sensitive information. keyId is a Graph - API credential-slot identifier (not the secret itself), but the debug log - for a malformed endDateTime must not include it regardless — the value - isn't needed to diagnose a date-parsing failure.""" + """CodeQL alert #31 (py/clear-text-logging-sensitive-data): the debug log + for a malformed endDateTime must not include the raw endDateTime value or + keyId — neither is needed to diagnose a date-parsing failure, and Graph + API credential fields should never be echoed into logs verbatim.""" sentinel_key_id = "sentinel-key-id-should-not-appear-in-logs" + sentinel_end_date = "sentinel-malformed-end-date-should-not-appear-in-logs" apps = { "value": [ { @@ -305,7 +306,7 @@ def test_idn_006_malformed_end_date_time_does_not_log_key_id(mock_azure, subscri "keyId": sentinel_key_id, "hint": "ab", "startDateTime": "2020-01-01T00:00:00Z", - "endDateTime": "not-a-valid-date", + "endDateTime": sentinel_end_date, } ], } @@ -318,6 +319,7 @@ def test_idn_006_malformed_end_date_time_does_not_log_key_id(mock_azure, subscri # Malformed endDateTime alone doesn't matter here: the secret is already stale by age. assert len(findings) == 1 assert sentinel_key_id not in caplog.text + assert sentinel_end_date not in caplog.text # ── AZ-IDN-007: active user with no MFA registered ────────────────────────── diff --git a/tests/test_signed_release_workflow.py b/tests/test_signed_release_workflow.py new file mode 100644 index 00000000..f296042a --- /dev/null +++ b/tests/test_signed_release_workflow.py @@ -0,0 +1,44 @@ +"""Safety checks for the signed release workflow.""" + +from pathlib import Path + +import yaml + + +WORKFLOW = Path(__file__).parents[1] / ".github" / "workflows" / "release.yml" + + +def _workflow(): + return yaml.safe_load(WORKFLOW.read_text(encoding="utf-8")) + + +def test_release_workflow_has_keyless_attestation_permissions(): + assert _workflow()["permissions"] == { + "contents": "write", + "id-token": "write", + "attestations": "write", + } + + +def test_release_requires_verified_annotated_tag(): + source = WORKFLOW.read_text(encoding="utf-8") + assert 'object_type" != "tag"' in source + assert ".verification.verified" in source + assert 'verified" != "true"' in source + + +def test_release_attests_every_distributed_manifest(): + source = WORKFLOW.read_text(encoding="utf-8") + action = "actions/attest-build-provenance@0f67c3f4856b2e3261c31976d6725780e5e4c373" + assert source.count(action) == 3 + assert "openshield-${{ env.TAG }}.tar.gz" in source + assert "openshield-${{ env.TAG }}-sbom.cyclonedx.json" in source + assert "subject-path: dist/SHA256SUMS" in source + + +def test_release_artifact_is_deterministic_and_checksums_are_published(): + source = WORKFLOW.read_text(encoding="utf-8") + assert "git archive --format=tar" in source + assert "gzip --no-name" in source + assert "sha256sum" in source + assert "files: dist/*" in source From a126ae0f36a59182ed8286e2e98ed54eb0941651 Mon Sep 17 00:00:00 2001 From: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> Date: Wed, 5 Aug 2026 12:56:21 +0100 Subject: [PATCH 2/2] Security fixes: cryptography CVE-2026-69247 and other dependency patches (#227) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * chore: add skeleton files and requirements * fix: remove embedded git repo * Core Structure Created * feat: build complete core — scanner engine, 10 rules, API, playbooks, compliance mappings, docs * docs: replace ASCII architecture with interactive Mermaid diagram * feat: Sentinel integration — ingest.py, 4 KQL rules, setup guide (#12) * feat: add sentinel/ingest.py — Log Analytics ingestion via HMAC-SHA256 * feat: add sentinel/__init__.py * feat: add KQL rule — HIGH severity finding detected * feat: add KQL rule — misconfiguration wave detection * feat: add KQL rule — new resource type critical detection * Delete sentinel/rules directory * Create rules * Delete sentinel/rules * Add KQL rule for high severity findings * Add Misconfiguration Wave detection rule * Add KQL rule for persistent misconfiguration detection * Add KQL rule for new critical resource types This rule identifies new resource types with critical findings that have occurred in the last 24 hours, excluding known types from the last 30 days. * Add script to generate test findings in JSON format This script generates test findings related to security compliance and saves them in a JSON file. * Add Sentinel integration test plan and results Added a comprehensive test plan for Sentinel integration, detailing test objectives, results, and acceptance criteria for various KQL rules and data ingestion. * docs: add sentinel integration setup guide Added a comprehensive setup guide for integrating Sentinel with Azure, covering prerequisites, workspace creation, activation, environment variable setup, ingestion, log verification, KQL rules deployment, and incident verification. * fix: add AZ-STOR-003 compliance mappings, correct NIST control to PR.DS-3 * docs: add real-world breach scenarios for all 10 starter rules (#15) * feat: add AZ-KV-002 key vault public access rule and remediation playbook (#14) * docs: update README with rule count, roadmap progress and contributors * feat: add network security rules AZ-NET-003 to AZ-NET-010 (#16) * Add az_net_003.py to check NSG rules for port 443 This script detects Network Security Groups (NSGs) with unrestricted inbound access on port 443 and provides remediation guidance. * Add AZ-NET-004 rule for empty NSG detection This script detects Network Security Groups (NSGs) that have no custom security rules configured, providing details for remediation. * Add AZ-NET-005 rule for DDoS protection check This script detects virtual networks in Azure that do not have DDoS protection enabled and provides remediation steps. * feat: add rule AZ-NET-006 — public IP unassociated with any resource This rule detects public IP addresses that are not associated with any resource, providing details for remediation. * feat: add rule AZ-NET-007 — Application Gateway without WAF enabled This rule detects Application Gateways that do not have WAF enabled, logging findings and providing remediation steps. * feat: add rule AZ-NET-008 — load balancer with no backend pool This rule detects load balancers in Azure that are not configured with a backend pool, indicating potential misconfiguration or unnecessary costs. * feat: add rule AZ-NET-009 — VPN gateway using outdated IKE version This script detects VPN gateways using the outdated IKEv1 protocol and provides remediation steps to migrate to IKEv2. * feat: add rule AZ-NET-010 — subnet with no NSG attached This script detects subnets in Azure that do not have a Network Security Group (NSG) attached, logging findings and providing remediation guidance. * feat: add playbook fix_az_net_003.sh This script updates the NSG rule to restrict inbound traffic on port 443 to a specified IP range. * feat: add playbook fix_az_net_004.sh This script adds a default deny-all inbound rule to a specified NSG. * feat: add playbook fix_az_net_005.sh This script enables DDoS protection on a specified virtual network in Azure. It checks for required parameters and provides usage instructions if they are missing. * feat: add playbook fix_az_net_006.sh This script deletes unassociated public IP addresses in Azure. * feat: add playbook fix_az_net_007.sh This script enables WAF on an Application Gateway, ensuring compliance with the AZ-NET-007 rule. * feat: add playbook fix_az_net_008.sh Script to remediate AZ-NET-008 by deleting empty load balancers. * feat:add script to update VPN connection to IKEv2 This script updates a VPN connection to use IKEv2, ensuring compliance with the AZ-NET-009 rule. * feat: add playbook fix_az_net_010.sh This script attaches a specified network security group to a given subnet in a virtual network, ensuring compliance with the AZ-NET-010 rule. * Clarify description and add note for public-facing services Updated the description to clarify the risk of exposing port 443 and added a note regarding public-facing services. * Change severity level from MEDIUM to HIGH * fix: AZ-NET-005 severity changed to LOW — DDoS Standard high cost on small subscriptions * Add note about NetworkManagementClient usage Added a note regarding the creation of NetworkManagementClient directly and suggested a follow-up for consistency. * Add note about NetworkManagementClient usage Added a note regarding the use of NetworkManagementClient and suggested a follow-up for consistency. * Add additional security controls to CIS Azure benchmark * Refine control descriptions in nist_csf.json Updated descriptions for various controls to enhance clarity and specificity regarding remote access management, data protection, and security measures. * fix: add AZ-NET-003 to AZ-NET-010 to ISO27001 compliance framework Updated descriptions for various controls to clarify compliance requirements and improve security guidance. --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> * Feat/az stor 003 (#21) * feat: add rule AZ-STOR-003 storage lifecycle policy check * feat: add rule AZ-STOR-003 storage lifecycle policy check * docs: add SOC 2 Type II compliance framework mapping (#33) * docs: add SOC 2 Type II compliance framework mapping for all 20 rules Added SOC 2 Type II framework with detailed controls for security measures and compliance requirements. * feat: add soc2 to FRAMEWORK_FILE_MAP in finding.py add soc2.json to FRAMEWORK_FILE_MAP in finding.py * feat: add soc2 to SUPPORTED_FRAMEWORKS in compliance.py Added 'soc2' to the list of supported compliance frameworks. * Add SOC 2 controls for data protection and management * Refactor/azure client network methods (#22) * refactor: add get_virtual_networks() and get_public_ip_addresses() to AzureClient * Refactor DDoS protection check to use azure_client * refactor: AZ-NET-006 now uses azure_client.get_public_ip_addresses() * feat: add CI pipeline with 6 automated checks (#34) - Python syntax check on all rule files - Rule structure validation (RULE_ID, SEVERITY, FRAMEWORKS) + RULE_ID uniqueness - Hardcoded credential scan - Playbook existence + bash syntax check for every rule - Compliance JSON validation for all four framework files (inc. soc2.json) - API syntax check - Compliance vs rule cross-reference check - CI summary step with per-check pass/fail table (if: always) - Fix duplicate DESCRIPTION assignment in az_net_003.py - Add pyyaml to requirements.txt for local YAML validation - Add docs/ci-pipeline.md with local run commands and design rationale - Update CI_PIPELINE_GUIDE.md with final PR description Closes #30 * docs: update .github/ISSUE_TEMPLATE/new_rule.md to reflect current codebase state * docs: update .github/PULL_REQUEST_TEMPLATE.md to reflect current codebase state * docs: update CONTRIBUTING.md to reflect current codebase state * docs: update README.md to reflect current codebase state * docs: update compliance/frameworks/iso27001.json to reflect current codebase state * docs: update compliance/frameworks/nist_csf.json to reflect current codebase state * docs: update docs/adding-a-rule.md to reflect current codebase state * docs: update docs/architecture.md to reflect current codebase state * docs: update docs/az-stor-003-test-plan.md to reflect current codebase state * docs: update docs/azure-setup.md to reflect current codebase state * docs: update docs/ci-pipeline.md to reflect current codebase state * docs: update docs/sentinel-setup.md to reflect current codebase state * docs: update sentinel/TEST_PLAN.md to reflect current codebase state * docs: update docs/api-reference.md to reflect current codebase state * docs: update docs/rules-reference.md to reflect current codebase state * docs: update README.md for professional open source style * docs: update CONTRIBUTING.md for professional open source style * docs: update docs/adding-a-rule.md for professional open source style * docs: update deployment guide to use Render instead of Azure App Service * feat: add rule AZ-STOR-004 storage account diagnostic logging check (#39) * feat: add rule AZ-STOR-004 storage account diagnostic logging check Detects Azure storage accounts where diagnostic logging is not fully enabled on blob, queue, or table services. Emits one finding per non-compliant service (StorageRead, StorageWrite, StorageDelete must all be enabled). Adds get_storage_service_logging() to AzureClient using MonitorManagementClient. Includes remediation playbook that enables all three services in one run. Frameworks: CIS 3.3, NIST DE.CM-7, ISO 27001 A.12.4.1 * chore: add AZ-STOR-004 compliance mappings --------- Co-authored-by: Shaurya K Sharma * feat: add rule AZ-IDN-003 Adds scanner rule AZ-IDN-003 detecting Entra ID (#48) * feat: add scanner rule AZ-IDN-003 — guest user invitations not restricted to admins * feat: add remediation playbook fix_az_idn_003.sh This script restricts guest user invitations to only admins and users with the Guest Inviter role in Azure Active Directory. * feat: add AZ-IDN-003 to CIS compliance framework Added control for guest invite restrictions to enhance security. * feat: add AZ-IDN-003 to NIST compliance framework * feat: add AZ-IDN-003 to ISO27001 compliance framework Added control AZ-IDN-003 for user registration and de-registration process. * feat: add AZ-IDN-003 to SOC2 compliance framework * feat: add rule AZ-CMP-002 — VM disk not protected by CMK or ADE (#47) * feat: add scanner rule AZ-CMP-002 — VM disk not protected by CMK or ADE This script detects virtual machines whose disks use platform-managed encryption only and provides findings for compliance with CIS 7.2. * feat: add remediation playbook fix_az_cmp_002.sh This script enables Azure Disk Encryption on a specified virtual machine using a Key Vault for the disk encryption key. * feat: add AZ-CMP-002 to CIS compliance framework Added a new control for OS disk encryption requirements. * feat: add AZ-CMP-002 to NIST compliance framework * feat: add AZ-CMP-002 to ISO27001 compliance framework Added control AZ-CMP-002 regarding cryptographic controls policy and its requirements. * feat: add AZ-CMP-002 to SOC2 compliance framework * fix: correct indentation in CIS AZ-CMP-002 entry * feat: add remediation playbook fix_az_cmp_002.sh to correct location This script enables Azure Disk Encryption on a specified virtual machine using a provided Key Vault for disk encryption. * Delete fix_az_cmp_002.sh * Feat/api deployment (#46) * feat: deploy API to Render with security hardening and CI/CD optimizations * feat: finalize Render deployment with security hardening and Gunicorn import fix * fix: GitHub Actions syntax and secret detection logic in deploy workflow * ix: harden scan trigger route with detailed error handling and remove redundant DB initialization * fix: implement global database connection management and harden all API routes * ix: prevent insecure smoke tests on main branch by enforcing JWT_SECRET presence and prevent CI false negatives in playbook check by enforcing non-empty glob match * fix: resolve Render startup crash and harden scan serialization against recursive objects * fix: add missing six and cryptography dependencies for Azure SDK compatibility * fix: increase CI wait time for Render build and add missing msrest dependencies * feat: integrate real subscription ID into smoke tests and CI/CD pipeline * feat: integrate real Azure_ ID's into smoke tests and CI/CD pipeline * feat: add root welcome route to confirm API status * fix: resolve specific CI credential flags in code and workflow while maintaining documentation standards * fix: resolve IndentationError in CI compliance cross-reference check * fix: resolve dependency issue and test on deployment * fix: resolve somke test TC-21 * fix: RUN_REAL_SCAN not set → TC-13/TC-14 skip → 21/21 pass for new live API url test * fix: scan.py deferred import from scanner.engine import ScanEngine was running before the subscription_id check * fix: restrict deploy triggers to dev and main, enable RUN_REAL_SCAN for maintainer CI, and update test plan documentation * feat: AZ-NET-011 Network Watcher not enabled in all regions (#42) * feat: add AZ-NET-011 Network Watcher rule, playbook and compliance mappings * fix: add missing AzureClient methods, SOC2 mapping and fix playbook region * fix: add SOC2 CC7.2 to FRAMEWORKS in az_net_011.py * feat: add AZ-DB-003 PostgreSQL Flexible Server SSL enforcement rule a… (#49) * feat: add AZ-DB-003 PostgreSQL Flexible Server SSL enforcement rule and playbook * fix: correct requirements.txt formatting for postgresqlflexibleserver * fix: correct postgresqlflexibleservers package name and version * fix: handle empty params gracefully and clean up playbook output * [RULE] AZ-CMP-003: VM without endpoint protection installed (#57) * feat: add scanner rule AZ-CMP-003 — VM without endpoint protection installed This script scans Azure VMs to check for the presence of recognized endpoint protection extensions. It logs findings for VMs without the required protection. * feat: add remediation playbook fix_az_cmp_003.sh This script installs endpoint protection on Azure VMs based on the operating system specified. It supports both Linux and Windows VMs. * feat: add AZ-CMP-003 to CIS compliance framework * feat: add AZ-CMP-003 to NIST compliance framework * feat: add AZ-CMP-003 to ISO27001 compliance framework * feat: add AZ-CMP-003 to SOC2 compliance framework * feat: add get_vm_extensions method to AzureClient Add method to retrieve VM extensions for a given VM. * fix: correct indentation and return type in get_vm_extensions * Add 1 more space in the code * add 4 space beofre def Add method to retrieve VM extensions for a given VM. * [DOCS] Add OpenShield learning and onboarding portal (#51) * docs: add OpenShield learning portal * Fix formatting for Learn OpenShield section --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> * refactor: reuse database connection per request using Flask g (#41) * fix: improve scan routes error handling and database reuse * fix: add database connection reuse and DATABASE_URL validation to score.py * fix: add database connection reuse, DATABASE_URL validation, and FileNotFoundError handling to compliance.py * fix: enforce JWT_SECRET environment variable, remove hardcoded default * ci: trigger fresh CI run * fix: all requirements - g.db naming, teardown, close() method * docs: add security policy, issue template, and README badges (#64) * feat: add rule AZ-KV-004 Key Vault purge protection disabled (#55) * feat: add rule AZ-KV-004 Key Vault purge protection disabled * fix: address PR review feedback for AZ-KV-004 - Add SOC2 CC9.1 mapping to FRAMEWORKS dict - Add AZ-KV-004 entries to all four compliance framework JSON files - Add set -euo pipefail to playbook - Add resource_group to metadata dict * feat: add AZ-STOR-005 geo-redundant storage rule (#74) - scanner/rules/az_stor_005.py: detects storage accounts using LRS or ZRS (non-geo-redundant) replication; flags them as MEDIUM severity - playbooks/cli/fix_az_stor_005.sh: CLI remediation to update storage account SKU to a geo-redundant option (Standard_GRS by default); validates target SKU against allowed geo-redundant values - compliance/frameworks/*.json: adds AZ-STOR-005 entry to CIS Azure Benchmark (3.1), NIST CSF (PR.IP-4), ISO 27001 (A.17.2.1), and SOC 2 (A1.2) Closes #71 Co-authored-by: Shaurya K Sharma * feat: add rule AZ-DB-004 SQL Server firewall allows all Azure services (#70) * feat: add rule AZ-DB-004 SQL Server firewall allows all Azure services - Add scanner rule az_db_004.py detecting SQL Servers with Allow Azure services firewall rule enabled - Add remediation playbook fix_az_db_004.sh - Add get_sql_server_firewall_rules method to AzureClient - Add AZ-DB-004 entries to all four compliance framework JSON files * fix: add get_sql_server_firewall_rules to AzureClient * fix: remove duplicate import, fix indentation, add return None to auditing policy * docs: add 6 README badges (#79) * feat: add AZ-KV-005 Key Vault certificate expiring within 30 days (#75) * Remove duplicate import of MonitorManagementClient * Add method to get Key Vault certificates Added a new method to list certificates in a Key Vault. * Add AZ-KV-005 rule for expiring Key Vault certificates This script scans Azure Key Vaults for certificates that are expiring within 30 days and do not have auto-renewal enabled. It logs findings and provides remediation steps. * Add script to enable auto-renewal for Key Vault certificate This script enables auto-renewal for an expiring Key Vault certificate by updating its policy. * Add controls for Azure Key Vault security measures * Add AZ-KV-005 control for certificate maintenance * Add controls for key management and availability * Add SOC 2 controls for Azure Key Vault risk mitigation * Fix indentation in get_key_vaults method * Add azure-keyvault-certificates dependency * Enhance script error handling with pipefail option * Refactor lifetime_actions assignment for clarity * Add control for expiring certificate maintenance Added a new control for certificate maintenance in Azure Key Vault. * fix: add missing comma in soc2.json after AZ-KV-005 entry * fix: add missing comma in iso27001.json after AZ-KV-005 entry * [RULE] AZ-CMP-004: VM without automatic OS patching enabled (#73) * Added az_cmp_004.py to check VM patching status This script checks Azure VMs for automatic OS patching status and collects findings for those without it enabled. * Added script to enable automatic OS patching for VMs This script enables automatic OS patching for both Windows and Linux VMs in Azure. It requires a resource group and VM name as input, defaulting to Windows if the OS type is not specified. * Add control for OS patching requirement in CIS benchmark * Add vulnerability management control to NIST CSF * Added control AZ-CMP-004 for vulnerability management * Added SOC 2 controls for endpoint protection and OS patching * Fix JSON formatting in cis_azure_benchmark.json * Fix JSON formatting in nist_csf.json * Improve error handling in fix_az_cmp_004.sh Updated script to use 'set -euo pipefail' for better error handling. * Update patching condition for Windows configuration Refine condition for patching approval based on patch mode. * Fix indentation and formatting in az_cmp_004.py * feat: add AI provider abstraction layer for Anthropic, Groq and Gemini (#89) * feat: initialise api/services package * feat: add AI provider abstraction layer for Anthropic, Groq and Gemini * fix: add module docstring to ai_provider.py Added a docstring explaining the purpose of the AI provider abstraction layer. * fix: make model configurable with sensible defaults per provider * Smoke Test Alginment after the recent changes to the Repository causing the Deployment CI failure (#88) * fix: test align smoke tests with API behavior and environment * test: deploy.yml run after smoke test alginment * fix: smoke test aligned after recent codebase changes * feat: add AZ-IDN-004 PIM not configured for admin roles rule and play… (#77) * feat: add AZ-IDN-004 PIM not configured for admin roles rule and playbook * fix: fetch Graph API token once and reuse headers for both API calls * fix: correct malformed JSON in cis_azure_benchmark.json for AZ-IDN-004 entry --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> * feat: add AI executive summary and remediation endpoint (#95) * feat: add AI insights endpoint * ci: scan only quoted-literal credential assignments --------- Co-authored-by: Shaurya K Sharma * feat(scanner): add AZ-NET-014 VNet peering gateway transit rule (#94) - Add scanner/rules/az_net_014.py to detect VNet peerings with allowGatewayTransit or useRemoteGateways enabled - Add get_vnet_peerings() and get_azure_firewalls() to azure_client.py - Add playbooks/cli/fix_az_net_014.sh remediation script - Update all 4 compliance framework JSONs with AZ-NET-014 mappings * feat: add AZ-NET-013 Azure Firewall VNet rule (#99) Co-authored-by: Shaurya K Sharma * Implement AI Q&A over scan findings (#98) Co-authored-by: Shaurya K Sharma * Feat/CVE correlation (#96) * fix: smoke test aligned after recent codebase changes * feat: add CVE correlation via MITRE NVD API * fix: ensure the run migration logic handles edge cases * fix: sync with dev after merged PRs, fix compliance duplication, indentaion and omttion of AZ-STOR-04 * fix: CVE prefix mappings, use legacy-only enrichment, clean up tests, and align CVE correlation docs. * fix: findings DB cleanup, AI title fallback, and persist CVE enrichment * feat: add RAG powered AI insights layer with Azure security skill embeddings (#97) * Create __init__.py * Implement OpenShield vector store builder This script builds the OpenShield knowledge base vector store for RAG AI insights by collecting rules and compliance documents, then embedding them into a vector store. * Add AI insights routes for summary, prioritisation, and Q&A * Implement knowledge retrieval from vector store This module retrieves relevant knowledge from the OpenShield vector store for retrieval-augmented generation (RAG). It includes error handling for missing vector stores and the chromadb dependency. * Register AI blueprint in the Flask app * Add chromadb version 0.4.24 to requirements * feat: add Azure security skills into knowledge base for RAG embedding * feat: wire Azure skill documents into embedding pipeline * Add sentence-transformers version 2.7.0 to requirements * ignore generated ai vectorstore directory * Refactor AI insights routes for clarity and updates * fix: deduplicate ai_bp and restore missing score_bp import in app.py * Refactor severity handling and update prompts * merge dev into feat/rag-ai-insights, resolve ai.py conflict * trigger CI * Remove AZ-CMP-003 and update AZ-NET-014 description Removed control AZ-CMP-003 related to unauthorized software detection and updated control AZ-NET-014 description for clarity. * feat: add AZ-NET-012 - NSG flow logs not enabled rule (#76) * ci: trigger fresh CI run * Dev (#50) * chore: add skeleton files and requirements * fix: remove embedded git repo * Core Structure Created * feat: build complete core — scanner engine, 10 rules, API, playbooks, compliance mappings, docs * docs: replace ASCII architecture with interactive Mermaid diagram * feat: Sentinel integration — ingest.py, 4 KQL rules, setup guide (#12) * feat: add sentinel/ingest.py — Log Analytics ingestion via HMAC-SHA256 * feat: add sentinel/__init__.py * feat: add KQL rule — HIGH severity finding detected * feat: add KQL rule — misconfiguration wave detection * feat: add KQL rule — new resource type critical detection * Delete sentinel/rules directory * Create rules * Delete sentinel/rules * Add KQL rule for high severity findings * Add Misconfiguration Wave detection rule * Add KQL rule for persistent misconfiguration detection * Add KQL rule for new critical resource types This rule identifies new resource types with critical findings that have occurred in the last 24 hours, excluding known types from the last 30 days. * Add script to generate test findings in JSON format This script generates test findings related to security compliance and saves them in a JSON file. * Add Sentinel integration test plan and results Added a comprehensive test plan for Sentinel integration, detailing test objectives, results, and acceptance criteria for various KQL rules and data ingestion. * docs: add sentinel integration setup guide Added a comprehensive setup guide for integrating Sentinel with Azure, covering prerequisites, workspace creation, activation, environment variable setup, ingestion, log verification, KQL rules deployment, and incident verification. * fix: add AZ-STOR-003 compliance mappings, correct NIST control to PR.DS-3 * docs: add real-world breach scenarios for all 10 starter rules (#15) * feat: add AZ-KV-002 key vault public access rule and remediation playbook (#14) * docs: update README with rule count, roadmap progress and contributors * feat: add network security rules AZ-NET-003 to AZ-NET-010 (#16) * Add az_net_003.py to check NSG rules for port 443 This script detects Network Security Groups (NSGs) with unrestricted inbound access on port 443 and provides remediation guidance. * Add AZ-NET-004 rule for empty NSG detection This script detects Network Security Groups (NSGs) that have no custom security rules configured, providing details for remediation. * Add AZ-NET-005 rule for DDoS protection check This script detects virtual networks in Azure that do not have DDoS protection enabled and provides remediation steps. * feat: add rule AZ-NET-006 — public IP unassociated with any resource This rule detects public IP addresses that are not associated with any resource, providing details for remediation. * feat: add rule AZ-NET-007 — Application Gateway without WAF enabled This rule detects Application Gateways that do not have WAF enabled, logging findings and providing remediation steps. * feat: add rule AZ-NET-008 — load balancer with no backend pool This rule detects load balancers in Azure that are not configured with a backend pool, indicating potential misconfiguration or unnecessary costs. * feat: add rule AZ-NET-009 — VPN gateway using outdated IKE version This script detects VPN gateways using the outdated IKEv1 protocol and provides remediation steps to migrate to IKEv2. * feat: add rule AZ-NET-010 — subnet with no NSG attached This script detects subnets in Azure that do not have a Network Security Group (NSG) attached, logging findings and providing remediation guidance. * feat: add playbook fix_az_net_003.sh This script updates the NSG rule to restrict inbound traffic on port 443 to a specified IP range. * feat: add playbook fix_az_net_004.sh This script adds a default deny-all inbound rule to a specified NSG. * feat: add playbook fix_az_net_005.sh This script enables DDoS protection on a specified virtual network in Azure. It checks for required parameters and provides usage instructions if they are missing. * feat: add playbook fix_az_net_006.sh This script deletes unassociated public IP addresses in Azure. * feat: add playbook fix_az_net_007.sh This script enables WAF on an Application Gateway, ensuring compliance with the AZ-NET-007 rule. * feat: add playbook fix_az_net_008.sh Script to remediate AZ-NET-008 by deleting empty load balancers. * feat:add script to update VPN connection to IKEv2 This script updates a VPN connection to use IKEv2, ensuring compliance with the AZ-NET-009 rule. * feat: add playbook fix_az_net_010.sh This script attaches a specified network security group to a given subnet in a virtual network, ensuring compliance with the AZ-NET-010 rule. * Clarify description and add note for public-facing services Updated the description to clarify the risk of exposing port 443 and added a note regarding public-facing services. * Change severity level from MEDIUM to HIGH * fix: AZ-NET-005 severity changed to LOW — DDoS Standard high cost on small subscriptions * Add note about NetworkManagementClient usage Added a note regarding the creation of NetworkManagementClient directly and suggested a follow-up for consistency. * Add note about NetworkManagementClient usage Added a note regarding the use of NetworkManagementClient and suggested a follow-up for consistency. * Add additional security controls to CIS Azure benchmark * Refine control descriptions in nist_csf.json Updated descriptions for various controls to enhance clarity and specificity regarding remote access management, data protection, and security measures. * fix: add AZ-NET-003 to AZ-NET-010 to ISO27001 compliance framework Updated descriptions for various controls to clarify compliance requirements and improve security guidance. --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> * Feat/az stor 003 (#21) * feat: add rule AZ-STOR-003 storage lifecycle policy check * feat: add rule AZ-STOR-003 storage lifecycle policy check * docs: add SOC 2 Type II compliance framework mapping (#33) * docs: add SOC 2 Type II compliance framework mapping for all 20 rules Added SOC 2 Type II framework with detailed controls for security measures and compliance requirements. * feat: add soc2 to FRAMEWORK_FILE_MAP in finding.py add soc2.json to FRAMEWORK_FILE_MAP in finding.py * feat: add soc2 to SUPPORTED_FRAMEWORKS in compliance.py Added 'soc2' to the list of supported compliance frameworks. * Add SOC 2 controls for data protection and management * Refactor/azure client network methods (#22) * refactor: add get_virtual_networks() and get_public_ip_addresses() to AzureClient * Refactor DDoS protection check to use azure_client * refactor: AZ-NET-006 now uses azure_client.get_public_ip_addresses() * feat: add CI pipeline with 6 automated checks (#34) - Python syntax check on all rule files - Rule structure validation (RULE_ID, SEVERITY, FRAMEWORKS) + RULE_ID uniqueness - Hardcoded credential scan - Playbook existence + bash syntax check for every rule - Compliance JSON validation for all four framework files (inc. soc2.json) - API syntax check - Compliance vs rule cross-reference check - CI summary step with per-check pass/fail table (if: always) - Fix duplicate DESCRIPTION assignment in az_net_003.py - Add pyyaml to requirements.txt for local YAML validation - Add docs/ci-pipeline.md with local run commands and design rationale - Update CI_PIPELINE_GUIDE.md with final PR description Closes #30 * docs: update .github/ISSUE_TEMPLATE/new_rule.md to reflect current codebase state * docs: update .github/PULL_REQUEST_TEMPLATE.md to reflect current codebase state * docs: update CONTRIBUTING.md to reflect current codebase state * docs: update README.md to reflect current codebase state * docs: update compliance/frameworks/iso27001.json to reflect current codebase state * docs: update compliance/frameworks/nist_csf.json to reflect current codebase state * docs: update docs/adding-a-rule.md to reflect current codebase state * docs: update docs/architecture.md to reflect current codebase state * docs: update docs/az-stor-003-test-plan.md to reflect current codebase state * docs: update docs/azure-setup.md to reflect current codebase state * docs: update docs/ci-pipeline.md to reflect current codebase state * docs: update docs/sentinel-setup.md to reflect current codebase state * docs: update sentinel/TEST_PLAN.md to reflect current codebase state * docs: update docs/api-reference.md to reflect current codebase state * docs: update docs/rules-reference.md to reflect current codebase state * docs: update README.md for professional open source style * docs: update CONTRIBUTING.md for professional open source style * docs: update docs/adding-a-rule.md for professional open source style * docs: update deployment guide to use Render instead of Azure App Service * feat: add rule AZ-STOR-004 storage account diagnostic logging check (#39) * feat: add rule AZ-STOR-004 storage account diagnostic logging check Detects Azure storage accounts where diagnostic logging is not fully enabled on blob, queue, or table services. Emits one finding per non-compliant service (StorageRead, StorageWrite, StorageDelete must all be enabled). Adds get_storage_service_logging() to AzureClient using MonitorManagementClient. Includes remediation playbook that enables all three services in one run. Frameworks: CIS 3.3, NIST DE.CM-7, ISO 27001 A.12.4.1 * chore: add AZ-STOR-004 compliance mappings --------- Co-authored-by: Shaurya K Sharma * feat: add rule AZ-IDN-003 Adds scanner rule AZ-IDN-003 detecting Entra ID (#48) * feat: add scanner rule AZ-IDN-003 — guest user invitations not restricted to admins * feat: add remediation playbook fix_az_idn_003.sh This script restricts guest user invitations to only admins and users with the Guest Inviter role in Azure Active Directory. * feat: add AZ-IDN-003 to CIS compliance framework Added control for guest invite restrictions to enhance security. * feat: add AZ-IDN-003 to NIST compliance framework * feat: add AZ-IDN-003 to ISO27001 compliance framework Added control AZ-IDN-003 for user registration and de-registration process. * feat: add AZ-IDN-003 to SOC2 compliance framework * feat: add rule AZ-CMP-002 — VM disk not protected by CMK or ADE (#47) * feat: add scanner rule AZ-CMP-002 — VM disk not protected by CMK or ADE This script detects virtual machines whose disks use platform-managed encryption only and provides findings for compliance with CIS 7.2. * feat: add remediation playbook fix_az_cmp_002.sh This script enables Azure Disk Encryption on a specified virtual machine using a Key Vault for the disk encryption key. * feat: add AZ-CMP-002 to CIS compliance framework Added a new control for OS disk encryption requirements. * feat: add AZ-CMP-002 to NIST compliance framework * feat: add AZ-CMP-002 to ISO27001 compliance framework Added control AZ-CMP-002 regarding cryptographic controls policy and its requirements. * feat: add AZ-CMP-002 to SOC2 compliance framework * fix: correct indentation in CIS AZ-CMP-002 entry * feat: add remediation playbook fix_az_cmp_002.sh to correct location This script enables Azure Disk Encryption on a specified virtual machine using a provided Key Vault for disk encryption. * Delete fix_az_cmp_002.sh * Feat/api deployment (#46) * feat: deploy API to Render with security hardening and CI/CD optimizations * feat: finalize Render deployment with security hardening and Gunicorn import fix * fix: GitHub Actions syntax and secret detection logic in deploy workflow * ix: harden scan trigger route with detailed error handling and remove redundant DB initialization * fix: implement global database connection management and harden all API routes * ix: prevent insecure smoke tests on main branch by enforcing JWT_SECRET presence and prevent CI false negatives in playbook check by enforcing non-empty glob match * fix: resolve Render startup crash and harden scan serialization against recursive objects * fix: add missing six and cryptography dependencies for Azure SDK compatibility * fix: increase CI wait time for Render build and add missing msrest dependencies * feat: integrate real subscription ID into smoke tests and CI/CD pipeline * feat: integrate real Azure_ ID's into smoke tests and CI/CD pipeline * feat: add root welcome route to confirm API status * fix: resolve specific CI credential flags in code and workflow while maintaining documentation standards * fix: resolve IndentationError in CI compliance cross-reference check * fix: resolve dependency issue and test on deployment * fix: resolve somke test TC-21 * fix: RUN_REAL_SCAN not set → TC-13/TC-14 skip → 21/21 pass for new live API url test * fix: scan.py deferred import from scanner.engine import ScanEngine was running before the subscription_id check * fix: restrict deploy triggers to dev and main, enable RUN_REAL_SCAN for maintainer CI, and update test plan documentation * feat: AZ-NET-011 Network Watcher not enabled in all regions (#42) * feat: add AZ-NET-011 Network Watcher rule, playbook and compliance mappings * fix: add missing AzureClient methods, SOC2 mapping and fix playbook region * fix: add SOC2 CC7.2 to FRAMEWORKS in az_net_011.py * feat: add AZ-DB-003 PostgreSQL Flexible Server SSL enforcement rule a… (#49) * feat: add AZ-DB-003 PostgreSQL Flexible Server SSL enforcement rule and playbook * fix: correct requirements.txt formatting for postgresqlflexibleserver * fix: correct postgresqlflexibleservers package name and version * fix: handle empty params gracefully and clean up playbook output --------- Co-authored-by: Tanvir Farhad Co-authored-by: PARTH J ROHIT Co-authored-by: Ritik Sah Co-authored-by: Shaurya K Sharma Co-authored-by: Shaurya K Sharma Co-authored-by: Mahfuzur Rahman Emon * refactor: reuse database connection per request using Flask g (#41) * fix: improve scan routes error handling and database reuse * fix: add database connection reuse and DATABASE_URL validation to score.py * fix: add database connection reuse, DATABASE_URL validation, and FileNotFoundError handling to compliance.py * fix: enforce JWT_SECRET environment variable, remove hardcoded default * ci: trigger fresh CI run * fix: all requirements - g.db naming, teardown, close() method * fix: update az_net_012.py to match az_cmp_003 pattern and add set -euo pipefail to bash script * fix: correct az_net_012.py signature, add set -euo pipefail, add AZ-NET-012 to all compliance files * fix: correct az_net_012.py to match az_cmp_003 pattern --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> Co-authored-by: Tanvir Farhad Co-authored-by: PARTH J ROHIT Co-authored-by: Ritik Sah Co-authored-by: Shaurya K Sharma Co-authored-by: Shaurya K Sharma Co-authored-by: Mahfuzur Rahman Emon * fix: resolve CodeQL warnings in embed.py and test files * feat(frontend): build complete 7-page security dashboard (#111) * Basic components and pages with dummy data * feat(frontend): build complete 7-page security dashboard Complete React 18 + Vite frontend for OpenShield security platform. Pages (7): - Monitoring — security score gauge, trend chart, findings distribution, issues by resource group, category scores - Discovery — resource table with issue counts, risk filters, category grouping, resource group filtering, clickable category cards - Prioritization — risk vs effort matrix, ranked list with quick remediation preview, all 25 action items; click-to-select syncs matrix + action items + remediation panel - Detailed Scan — findings list with playbook tabs (portal/CLI/validation), navigates from Prioritization with context banner - Compliance — CIS/NIST/ISO27001/SOC2 framework cards, controls table, comparison trend chart, CSV/JSON export - Drift — configuration change timeline, ADDED/REMOVED/MODIFIED events with before/after values, who changed it and when - AI Assistant — 3-column layout (findings picker, chat, suggestions + CVE analysis + executive summary); AI chat wired to aiApi.js with smart mock responses; finding context passed from Scan page API service layer (src/utils/api.js): - Demo/Live mode toggle persisted in localStorage - JWT token bootstrap in App.jsx - Health check on startup with auto-fallback to demo mode - Real fetch calls with mock fallback for every endpoint: /api/score, /api/findings, /api/findings/:id, /api/findings/:id/playbook, /api/resources, /api/prioritization, /api/drift, /api/scans, /api/scans/trigger, /api/scans/:id, /api/compliance/cis|nist|iso27001 - snake_case → camelCase normalisation for all backend responses - Separate aiApi.js for AI endpoints with smart mock responses Header features: - Run Scan button with live polling (4s interval, 5-min timeout, elapsed timer) - Demo/Live badge with connection test before switching - Error popup if backend is unreachable Design system: - Tailwind CSS v3 with custom tokens (brand, severity, bg-dark, status) - Dark mode via class strategy, persisted in localStorage - Fully responsive — mobile hamburger drawer, stacked layouts on sm - Dot-pattern background, soft shadows, consistent 4px grid Mock data: - 8 api.*.json files matching exact backend response schema - API_ENDPOINTS.txt — backend contract document with implementation status, database schema, seed data, and endpoint ordering guide Co-Authored-By: Claude Sonnet 4.6 * feat(frontend): wire live backend, fix JWT auth, add Vercel deployment config - Fix JWT: read VITE_JWT_TOKEN env var so live API calls authenticate correctly (was sending plain string 'dev-demo-token' which backend rejected as invalid JWT) - Add vercel.json with SPA rewrites so /monitoring, /scan etc don't 404 - Monitoring page now fetches real score + findings in live mode and computes stats/distribution/resource-group breakdown from actual backend data - Run Scan button shows subscription ID input in live mode (optional — backend falls back to AZURE_SUBSCRIPTION_ID env var if blank) - api.js: no silent localhost fallback in production builds (fails loudly if VITE_API_URL is not set) --------- Co-authored-by: Claude Sonnet 4.6 * Feat/jwt secret prod fail closed (#117) * fix: smoke test aligned after recent codebase changes * feat: fail closed on insecure JWT_SECRET in production * fix: rename _DEFAULT_JWT_SECRET to avoid CI credential scanner false positive * feat: AI-004 RAG Pipeline - Document Ingestion and Vector Store (#104) * feat: add AZ-IDN-004 PIM not configured for admin roles rule and playbook * feat: add RAG pipeline with document loader, chunker, embedder, ChromaDB vector store and Flask API routes * fix: remove duplicate ai files, restore deleted compliance rules, revert requirements to chromadb 0.4.24 * fix: update gitignore to use ai/vectorstore/ and clean up README references * fix: add missing newline at EOF in compliance JSON files * Potential fix for pull request finding 'Unused import' Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> * feat: add PQC compliance mappings, azure client methods and dependencies * docs: update README with post-quantum cryptography scanning and rule count * Feat/live data wiring (#122) * fix: smoke test aligned after recent codebase changes * feat: wire live backend, implement missing endpoints, fix deploy crash - api.js/aiApi.js: default to live mode, hardcode Render URL fallback, non-persisted cold-start fallback, fix isDemoOrUnconfigured check - App.jsx: retry health probe 5x15s for Render cold start - AILayer.jsx: add catch to Promise.all so summary spinner always clears - scanner/engine.py: add status completed to scan result - api/routes/resources.py: new GET /api/resources from findings - api/routes/prioritization.py: new GET /api/prioritization ranked by score - api/routes/drift.py: new GET /api/drift from scan comparison - api/routes/findings.py: new GET /api/findings/:id/playbook from cli scripts - api/app.py: remove duplicate module-level ai_bp import that crashed gunicorn - requirements.txt: pin numpy<2.0 to fix chromadb startup crash on Render - deploy.yml: add feat/live-data-wiring to push triggers * fix: make all GET /api/* endpoints public for demo dashboard removes JWT requirement from read-only routes so the Vercel frontend works without VITE_JWT_TOKEN; POST endpoints remain protected * fix: update smoke tests for public GET auth model, accept scan timeout - TC-18/19: switched from GET /api/findings (now public) to POST /api/scans/trigger which still requires JWT — better security coverage - TC-21: added status 0 as acceptable outcome; when AZURE_SUBSCRIPTION_ID is set on Render the server starts a real scan and the 45s client timeout fires before it completes — that is not a crash - app.py: all GET /api/* public, POST endpoints remain JWT-protected * feat: image/video support, drag-drop upload, Vercel-ready config, full README - assets/blog/.gitkeep: track empty directory for blog images - vercel.json: CSP allows Tailwind/Lucide CDNs and YouTube/Vimeo iframes; X-Frame-Options changed to SAMEORIGIN; Permissions-Policy added - script.js: real drag-and-drop on image upload zone with visual feedback - script.js: image size limit fixed from 2MB to 700KB with clear error (GitHub Contents API rejects base64 payloads over 1MB) - script.js: toEmbedUrl() converts YouTube watch URLs and Vimeo URLs to embed URLs automatically - script.js: blog posts render video embed above content if video field set - script.js: editor preview shows video iframe in real time - script.js: blog editor saves video embed URL to content entry - index.html: Video Embed URL field added to blog editor (YouTube/Vimeo) - index.html: image upload zone has id for drag-drop wiring - README.md: full maintainer guide — deployment, all content types, image/video guidelines, rules gallery update process, editor coverage table * fix: apply CORS to all routes not just /api/* so /health is accessible from Vercel * fix: scope score/findings/cve-summary to latest scan, make last-scanned dynamic - finding.py get_score(): was counting ALL findings across ALL scans — 3 seeded scans with ~37 findings total drove score to 0; now scoped to latest scan_id only - finding.py get_cve_summary(): same fix — latest scan scope - finding.py get_findings(): when no scan_id filter given, default to latest scan so dashboard shows current posture not historical accumulation - Header.jsx: replace hardcoded 'May 29, 2026 6:00 PM' with dynamic fetch from api.getScans() on mount, formatted in user local timezone * feat: implement resources, prioritization, drift, playbook endpoints; remove frontend mock data * fix: always prefer VITE_JWT_TOKEN over stale localStorage value * fix: compliance trend from scan history, fix AI tab crash * merge: resolve final README conflict in roadmap checklist * feat: add PQC to discovery icon map and website rules gallery * Feat/decouple CVE enrichment (#127) * fix: smoke test aligned after recent codebase changes * feat: decouple CVE enrichment into dedicated on-demand endpoint * feat: decouple CVE enrichment into dedicated on-demand endpoint adressed feedback * docs: update OpenShield Learn content, navigation, and hosting support (#126) * feat: add AZ-PQC-001 to AZ-PQC-003 post-quantum cryptography scanner rules (#121) * chore: add skeleton files and requirements * fix: remove embedded git repo * Core Structure Created * feat: build complete core — scanner engine, 10 rules, API, playbooks, compliance mappings, docs * docs: replace ASCII architecture with interactive Mermaid diagram * feat: Sentinel integration — ingest.py, 4 KQL rules, setup guide (#12) * feat: add sentinel/ingest.py — Log Analytics ingestion via HMAC-SHA256 * feat: add sentinel/__init__.py * feat: add KQL rule — HIGH severity finding detected * feat: add KQL rule — misconfiguration wave detection * feat: add KQL rule — new resource type critical detection * Delete sentinel/rules directory * Create rules * Delete sentinel/rules * Add KQL rule for high severity findings * Add Misconfiguration Wave detection rule * Add KQL rule for persistent misconfiguration detection * Add KQL rule for new critical resource types This rule identifies new resource types with critical findings that have occurred in the last 24 hours, excluding known types from the last 30 days. * Add script to generate test findings in JSON format This script generates test findings related to security compliance and saves them in a JSON file. * Add Sentinel integration test plan and results Added a comprehensive test plan for Sentinel integration, detailing test objectives, results, and acceptance criteria for various KQL rules and data ingestion. * docs: add sentinel integration setup guide Added a comprehensive setup guide for integrating Sentinel with Azure, covering prerequisites, workspace creation, activation, environment variable setup, ingestion, log verification, KQL rules deployment, and incident verification. * fix: add AZ-STOR-003 compliance mappings, correct NIST control to PR.DS-3 * docs: add real-world breach scenarios for all 10 starter rules (#15) * feat: add AZ-KV-002 key vault public access rule and remediation playbook (#14) * docs: update README with rule count, roadmap progress and contributors * feat: add network security rules AZ-NET-003 to AZ-NET-010 (#16) * Add az_net_003.py to check NSG rules for port 443 This script detects Network Security Groups (NSGs) with unrestricted inbound access on port 443 and provides remediation guidance. * Add AZ-NET-004 rule for empty NSG detection This script detects Network Security Groups (NSGs) that have no custom security rules configured, providing details for remediation. * Add AZ-NET-005 rule for DDoS protection check This script detects virtual networks in Azure that do not have DDoS protection enabled and provides remediation steps. * feat: add rule AZ-NET-006 — public IP unassociated with any resource This rule detects public IP addresses that are not associated with any resource, providing details for remediation. * feat: add rule AZ-NET-007 — Application Gateway without WAF enabled This rule detects Application Gateways that do not have WAF enabled, logging findings and providing remediation steps. * feat: add rule AZ-NET-008 — load balancer with no backend pool This rule detects load balancers in Azure that are not configured with a backend pool, indicating potential misconfiguration or unnecessary costs. * feat: add rule AZ-NET-009 — VPN gateway using outdated IKE version This script detects VPN gateways using the outdated IKEv1 protocol and provides remediation steps to migrate to IKEv2. * feat: add rule AZ-NET-010 — subnet with no NSG attached This script detects subnets in Azure that do not have a Network Security Group (NSG) attached, logging findings and providing remediation guidance. * feat: add playbook fix_az_net_003.sh This script updates the NSG rule to restrict inbound traffic on port 443 to a specified IP range. * feat: add playbook fix_az_net_004.sh This script adds a default deny-all inbound rule to a specified NSG. * feat: add playbook fix_az_net_005.sh This script enables DDoS protection on a specified virtual network in Azure. It checks for required parameters and provides usage instructions if they are missing. * feat: add playbook fix_az_net_006.sh This script deletes unassociated public IP addresses in Azure. * feat: add playbook fix_az_net_007.sh This script enables WAF on an Application Gateway, ensuring compliance with the AZ-NET-007 rule. * feat: add playbook fix_az_net_008.sh Script to remediate AZ-NET-008 by deleting empty load balancers. * feat:add script to update VPN connection to IKEv2 This script updates a VPN connection to use IKEv2, ensuring compliance with the AZ-NET-009 rule. * feat: add playbook fix_az_net_010.sh This script attaches a specified network security group to a given subnet in a virtual network, ensuring compliance with the AZ-NET-010 rule. * Clarify description and add note for public-facing services Updated the description to clarify the risk of exposing port 443 and added a note regarding public-facing services. * Change severity level from MEDIUM to HIGH * fix: AZ-NET-005 severity changed to LOW — DDoS Standard high cost on small subscriptions * Add note about NetworkManagementClient usage Added a note regarding the creation of NetworkManagementClient directly and suggested a follow-up for consistency. * Add note about NetworkManagementClient usage Added a note regarding the use of NetworkManagementClient and suggested a follow-up for consistency. * Add additional security controls to CIS Azure benchmark * Refine control descriptions in nist_csf.json Updated descriptions for various controls to enhance clarity and specificity regarding remote access management, data protection, and security measures. * fix: add AZ-NET-003 to AZ-NET-010 to ISO27001 compliance framework Updated descriptions for various controls to clarify compliance requirements and improve security guidance. --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> * Feat/az stor 003 (#21) * feat: add rule AZ-STOR-003 storage lifecycle policy check * feat: add rule AZ-STOR-003 storage lifecycle policy check * docs: add SOC 2 Type II compliance framework mapping (#33) * docs: add SOC 2 Type II compliance framework mapping for all 20 rules Added SOC 2 Type II framework with detailed controls for security measures and compliance requirements. * feat: add soc2 to FRAMEWORK_FILE_MAP in finding.py add soc2.json to FRAMEWORK_FILE_MAP in finding.py * feat: add soc2 to SUPPORTED_FRAMEWORKS in compliance.py Added 'soc2' to the list of supported compliance frameworks. * Add SOC 2 controls for data protection and management * Refactor/azure client network methods (#22) * refactor: add get_virtual_networks() and get_public_ip_addresses() to AzureClient * Refactor DDoS protection check to use azure_client * refactor: AZ-NET-006 now uses azure_client.get_public_ip_addresses() * feat: add CI pipeline with 6 automated checks (#34) - Python syntax check on all rule files - Rule structure validation (RULE_ID, SEVERITY, FRAMEWORKS) + RULE_ID uniqueness - Hardcoded credential scan - Playbook existence + bash syntax check for every rule - Compliance JSON validation for all four framework files (inc. soc2.json) - API syntax check - Compliance vs rule cross-reference check - CI summary step with per-check pass/fail table (if: always) - Fix duplicate DESCRIPTION assignment in az_net_003.py - Add pyyaml to requirements.txt for local YAML validation - Add docs/ci-pipeline.md with local run commands and design rationale - Update CI_PIPELINE_GUIDE.md with final PR description Closes #30 * docs: update .github/ISSUE_TEMPLATE/new_rule.md to reflect current codebase state * docs: update .github/PULL_REQUEST_TEMPLATE.md to reflect current codebase state * docs: update CONTRIBUTING.md to reflect current codebase state * docs: update README.md to reflect current codebase state * docs: update compliance/frameworks/iso27001.json to reflect current codebase state * docs: update compliance/frameworks/nist_csf.json to reflect current codebase state * docs: update docs/adding-a-rule.md to reflect current codebase state * docs: update docs/architecture.md to reflect current codebase state * docs: update docs/az-stor-003-test-plan.md to reflect current codebase state * docs: update docs/azure-setup.md to reflect current codebase state * docs: update docs/ci-pipeline.md to reflect current codebase state * docs: update docs/sentinel-setup.md to reflect current codebase state * docs: update sentinel/TEST_PLAN.md to reflect current codebase state * docs: update docs/api-reference.md to reflect current codebase state * docs: update docs/rules-reference.md to reflect current codebase state * docs: update README.md for professional open source style * docs: update CONTRIBUTING.md for professional open source style * docs: update docs/adding-a-rule.md for professional open source style * docs: update deployment guide to use Render instead of Azure App Service * feat: add rule AZ-STOR-004 storage account diagnostic logging check (#39) * feat: add rule AZ-STOR-004 storage account diagnostic logging check Detects Azure storage accounts where diagnostic logging is not fully enabled on blob, queue, or table services. Emits one finding per non-compliant service (StorageRead, StorageWrite, StorageDelete must all be enabled). Adds get_storage_service_logging() to AzureClient using MonitorManagementClient. Includes remediation playbook that enables all three services in one run. Frameworks: CIS 3.3, NIST DE.CM-7, ISO 27001 A.12.4.1 * chore: add AZ-STOR-004 compliance mappings --------- Co-authored-by: Shaurya K Sharma * feat: add rule AZ-IDN-003 Adds scanner rule AZ-IDN-003 detecting Entra ID (#48) * feat: add scanner rule AZ-IDN-003 — guest user invitations not restricted to admins * feat: add remediation playbook fix_az_idn_003.sh This script restricts guest user invitations to only admins and users with the Guest Inviter role in Azure Active Directory. * feat: add AZ-IDN-003 to CIS compliance framework Added control for guest invite restrictions to enhance security. * feat: add AZ-IDN-003 to NIST compliance framework * feat: add AZ-IDN-003 to ISO27001 compliance framework Added control AZ-IDN-003 for user registration and de-registration process. * feat: add AZ-IDN-003 to SOC2 compliance framework * feat: add rule AZ-CMP-002 — VM disk not protected by CMK or ADE (#47) * feat: add scanner rule AZ-CMP-002 — VM disk not protected by CMK or ADE This script detects virtual machines whose disks use platform-managed encryption only and provides findings for compliance with CIS 7.2. * feat: add remediation playbook fix_az_cmp_002.sh This script enables Azure Disk Encryption on a specified virtual machine using a Key Vault for the disk encryption key. * feat: add AZ-CMP-002 to CIS compliance framework Added a new control for OS disk encryption requirements. * feat: add AZ-CMP-002 to NIST compliance framework * feat: add AZ-CMP-002 to ISO27001 compliance framework Added control AZ-CMP-002 regarding cryptographic controls policy and its requirements. * feat: add AZ-CMP-002 to SOC2 compliance framework * fix: correct indentation in CIS AZ-CMP-002 entry * feat: add remediation playbook fix_az_cmp_002.sh to correct location This script enables Azure Disk Encryption on a specified virtual machine using a provided Key Vault for disk encryption. * Delete fix_az_cmp_002.sh * Feat/api deployment (#46) * feat: deploy API to Render with security hardening and CI/CD optimizations * feat: finalize Render deployment with security hardening and Gunicorn import fix * fix: GitHub Actions syntax and secret detection logic in deploy workflow * ix: harden scan trigger route with detailed error handling and remove redundant DB initialization * fix: implement global database connection management and harden all API routes * ix: prevent insecure smoke tests on main branch by enforcing JWT_SECRET presence and prevent CI false negatives in playbook check by enforcing non-empty glob match * fix: resolve Render startup crash and harden scan serialization against recursive objects * fix: add missing six and cryptography dependencies for Azure SDK compatibility * fix: increase CI wait time for Render build and add missing msrest dependencies * feat: integrate real subscription ID into smoke tests and CI/CD pipeline * feat: integrate real Azure_ ID's into smoke tests and CI/CD pipeline * feat: add root welcome route to confirm API status * fix: resolve specific CI credential flags in code and workflow while maintaining documentation standards * fix: resolve IndentationError in CI compliance cross-reference check * fix: resolve dependency issue and test on deployment * fix: resolve somke test TC-21 * fix: RUN_REAL_SCAN not set → TC-13/TC-14 skip → 21/21 pass for new live API url test * fix: scan.py deferred import from scanner.engine import ScanEngine was running before the subscription_id check * fix: restrict deploy triggers to dev and main, enable RUN_REAL_SCAN for maintainer CI, and update test plan documentation * feat: AZ-NET-011 Network Watcher not enabled in all regions (#42) * feat: add AZ-NET-011 Network Watcher rule, playbook and compliance mappings * fix: add missing AzureClient methods, SOC2 mapping and fix playbook region * fix: add SOC2 CC7.2 to FRAMEWORKS in az_net_011.py * feat: add AZ-DB-003 PostgreSQL Flexible Server SSL enforcement rule a… (#49) * feat: add AZ-DB-003 PostgreSQL Flexible Server SSL enforcement rule and playbook * fix: correct requirements.txt formatting for postgresqlflexibleserver * fix: correct postgresqlflexibleservers package name and version * fix: handle empty params gracefully and clean up playbook output * [RULE] AZ-CMP-003: VM without endpoint protection installed (#57) * feat: add scanner rule AZ-CMP-003 — VM without endpoint protection installed This script scans Azure VMs to check for the presence of recognized endpoint protection extensions. It logs findings for VMs without the required protection. * feat: add remediation playbook fix_az_cmp_003.sh This script installs endpoint protection on Azure VMs based on the operating system specified. It supports both Linux and Windows VMs. * feat: add AZ-CMP-003 to CIS compliance framework * feat: add AZ-CMP-003 to NIST compliance framework * feat: add AZ-CMP-003 to ISO27001 compliance framework * feat: add AZ-CMP-003 to SOC2 compliance framework * feat: add get_vm_extensions method to AzureClient Add method to retrieve VM extensions for a given VM. * fix: correct indentation and return type in get_vm_extensions * Add 1 more space in the code * add 4 space beofre def Add method to retrieve VM extensions for a given VM. * [DOCS] Add OpenShield learning and onboarding portal (#51) * docs: add OpenShield learning portal * Fix formatting for Learn OpenShield section --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> * refactor: reuse database connection per request using Flask g (#41) * fix: improve scan routes error handling and database reuse * fix: add database connection reuse and DATABASE_URL validation to score.py * fix: add database connection reuse, DATABASE_URL validation, and FileNotFoundError handling to compliance.py * fix: enforce JWT_SECRET environment variable, remove hardcoded default * ci: trigger fresh CI run * fix: all requirements - g.db naming, teardown, close() method * docs: add security policy, issue template, and README badges (#64) * feat: add rule AZ-KV-004 Key Vault purge protection disabled (#55) * feat: add rule AZ-KV-004 Key Vault purge protection disabled * fix: address PR review feedback for AZ-KV-004 - Add SOC2 CC9.1 mapping to FRAMEWORKS dict - Add AZ-KV-004 entries to all four compliance framework JSON files - Add set -euo pipefail to playbook - Add resource_group to metadata dict * feat: add AZ-STOR-005 geo-redundant storage rule (#74) - scanner/rules/az_stor_005.py: detects storage accounts using LRS or ZRS (non-geo-redundant) replication; flags them as MEDIUM severity - playbooks/cli/fix_az_stor_005.sh: CLI remediation to update storage account SKU to a geo-redundant option (Standard_GRS by default); validates target SKU against allowed geo-redundant values - compliance/frameworks/*.json: adds AZ-STOR-005 entry to CIS Azure Benchmark (3.1), NIST CSF (PR.IP-4), ISO 27001 (A.17.2.1), and SOC 2 (A1.2) Closes #71 Co-authored-by: Shaurya K Sharma * feat: add rule AZ-DB-004 SQL Server firewall allows all Azure services (#70) * feat: add rule AZ-DB-004 SQL Server firewall allows all Azure services - Add scanner rule az_db_004.py detecting SQL Servers with Allow Azure services firewall rule enabled - Add remediation playbook fix_az_db_004.sh - Add get_sql_server_firewall_rules method to AzureClient - Add AZ-DB-004 entries to all four compliance framework JSON files * fix: add get_sql_server_firewall_rules to AzureClient * fix: remove duplicate import, fix indentation, add return None to auditing policy * docs: add 6 README badges (#79) * feat: add AZ-KV-005 Key Vault certificate expiring within 30 days (#75) * Remove duplicate import of MonitorManagementClient * Add method to get Key Vault certificates Added a new method to list certificates in a Key Vault. * Add AZ-KV-005 rule for expiring Key Vault certificates This script scans Azure Key Vaults for certificates that are expiring within 30 days and do not have auto-renewal enabled. It logs findings and provides remediation steps. * Add script to enable auto-renewal for Key Vault certificate This script enables auto-renewal for an expiring Key Vault certificate by updating its policy. * Add controls for Azure Key Vault security measures * Add AZ-KV-005 control for certificate maintenance * Add controls for key management and availability * Add SOC 2 controls for Azure Key Vault risk mitigation * Fix indentation in get_key_vaults method * Add azure-keyvault-certificates dependency * Enhance script error handling with pipefail option * Refactor lifetime_actions assignment for clarity * Add control for expiring certificate maintenance Added a new control for certificate maintenance in Azure Key Vault. * fix: add missing comma in soc2.json after AZ-KV-005 entry * fix: add missing comma in iso27001.json after AZ-KV-005 entry * [RULE] AZ-CMP-004: VM without automatic OS patching enabled (#73) * Added az_cmp_004.py to check VM patching status This script checks Azure VMs for automatic OS patching status and collects findings for those without it enabled. * Added script to enable automatic OS patching for VMs This script enables automatic OS patching for both Windows and Linux VMs in Azure. It requires a resource group and VM name as input, defaulting to Windows if the OS type is not specified. * Add control for OS patching requirement in CIS benchmark * Add vulnerability management control to NIST CSF * Added control AZ-CMP-004 for vulnerability management * Added SOC 2 controls for endpoint protection and OS patching * Fix JSON formatting in cis_azure_benchmark.json * Fix JSON formatting in nist_csf.json * Improve error handling in fix_az_cmp_004.sh Updated script to use 'set -euo pipefail' for better error handling. * Update patching condition for Windows configuration Refine condition for patching approval based on patch mode. * Fix indentation and formatting in az_cmp_004.py * feat: add AI provider abstraction layer for Anthropic, Groq and Gemini (#89) * feat: initialise api/services package * feat: add AI provider abstraction layer for Anthropic, Groq and Gemini * fix: add module docstring to ai_provider.py Added a docstring explaining the purpose of the AI provider abstraction layer. * fix: make model configurable with sensible defaults per provider * Smoke Test Alginment after the recent changes to the Repository causing the Deployment CI failure (#88) * fix: test align smoke tests with API behavior and environment * test: deploy.yml run after smoke test alginment * fix: smoke test aligned after recent codebase changes * feat: add AZ-IDN-004 PIM not configured for admin roles rule and play… (#77) * feat: add AZ-IDN-004 PIM not configured for admin roles rule and playbook * fix: fetch Graph API token once and reuse headers for both API calls * fix: correct malformed JSON in cis_azure_benchmark.json for AZ-IDN-004 entry --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> * feat: add AI executive summary and remediation endpoint (#95) * feat: add AI insights endpoint * ci: scan only quoted-literal credential assignments --------- Co-authored-by: Shaurya K Sharma * feat(scanner): add AZ-NET-014 VNet peering gateway transit rule (#94) - Add scanner/rules/az_net_014.py to detect VNet peerings with allowGatewayTransit or useRemoteGateways enabled - Add get_vnet_peerings() and get_azure_firewalls() to azure_client.py - Add playbooks/cli/fix_az_net_014.sh remediation script - Update all 4 compliance framework JSONs with AZ-NET-014 mappings * feat: add AZ-NET-013 Azure Firewall VNet rule (#99) Co-authored-by: Shaurya K Sharma * Implement AI Q&A over scan findings (#98) Co-authored-by: Shaurya K Sharma * Feat/CVE correlation (#96) * fix: smoke test aligned after recent codebase changes * feat: add CVE correlation via MITRE NVD API * fix: ensure the run migration logic handles edge cases * fix: sync with dev after merged PRs, fix compliance duplication, indentaion and omttion of AZ-STOR-04 * fix: CVE prefix mappings, use legacy-only enrichment, clean up tests, and align CVE correlation docs. * fix: findings DB cleanup, AI title fallback, and persist CVE enrichment * feat: add RAG powered AI insights layer with Azure security skill embeddings (#97) * Create __init__.py * Implement OpenShield vector store builder This script builds the OpenShield knowledge base vector store for RAG AI insights by collecting rules and compliance documents, then embedding them into a vector store. * Add AI insights routes for summary, prioritisation, and Q&A * Implement knowledge retrieval from vector store This module retrieves relevant knowledge from the OpenShield vector store for retrieval-augmented generation (RAG). It includes error handling for missing vector stores and the chromadb dependency. * Register AI blueprint in the Flask app * Add chromadb version 0.4.24 to requirements * feat: add Azure security skills into knowledge base for RAG embedding * feat: wire Azure skill documents into embedding pipeline * Add sentence-transformers version 2.7.0 to requirements * ignore generated ai vectorstore directory * Refactor AI insights routes for clarity and updates * fix: deduplicate ai_bp and restore missing score_bp import in app.py * Refactor severity handling and update prompts * merge dev into feat/rag-ai-insights, resolve ai.py conflict * trigger CI * Remove AZ-CMP-003 and update AZ-NET-014 description Removed control AZ-CMP-003 related to unauthorized software detection and updated control AZ-NET-014 description for clarity. * feat: add AZ-NET-012 - NSG flow logs not enabled rule (#76) * ci: trigger fresh CI run * Dev (#50) * chore: add skeleton files and requirements * fix: remove embedded git repo * Core Structure Created * feat: build complete core — scanner engine, 10 rules, API, playbooks, compliance mappings, docs * docs: replace ASCII architecture with interactive Mermaid diagram * feat: Sentinel integration — ingest.py, 4 KQL rules, setup guide (#12) * feat: add sentinel/ingest.py — Log Analytics ingestion via HMAC-SHA256 * feat: add sentinel/__init__.py * feat: add KQL rule — HIGH severity finding detected * feat: add KQL rule — misconfiguration wave detection * feat: add KQL rule — new resource type critical detection * Delete sentinel/rules directory * Create rules * Delete sentinel/rules * Add KQL rule for high severity findings * Add Misconfiguration Wave detection rule * Add KQL rule for persistent misconfiguration detection * Add KQL rule for new critical resource types This rule identifies new resource types with critical findings that have occurred in the last 24 hours, excluding known types from the last 30 days. * Add script to generate test findings in JSON format This script generates test findings related to security compliance and saves them in a JSON file. * Add Sentinel integration test plan and results Added a comprehensive test plan for Sentinel integration, detailing test objectives, results, and acceptance criteria for various KQL rules and data ingestion. * docs: add sentinel integration setup guide Added a comprehensive setup guide for integrating Sentinel with Azure, covering prerequisites, workspace creation, activation, environment variable setup, ingestion, log verification, KQL rules deployment, and incident verification. * fix: add AZ-STOR-003 compliance mappings, correct NIST control to PR.DS-3 * docs: add real-world breach scenarios for all 10 starter rules (#15) * feat: add AZ-KV-002 key vault public access rule and remediation playbook (#14) * docs: update README with rule count, roadmap progress and contributors * feat: add network security rules AZ-NET-003 to AZ-NET-010 (#16) * Add az_net_003.py to check NSG rules for port 443 This script detects Network Security Groups (NSGs) with unrestricted inbound access on port 443 and provides remediation guidance. * Add AZ-NET-004 rule for empty NSG detection This script detects Network Security Groups (NSGs) that have no custom security rules configured, providing details for remediation. * Add AZ-NET-005 rule for DDoS protection check This script detects virtual networks in Azure that do not have DDoS protection enabled and provides remediation steps. * feat: add rule AZ-NET-006 — public IP unassociated with any resource This rule detects public IP addresses that are not associated with any resource, providing details for remediation. * feat: add rule AZ-NET-007 — Application Gateway without WAF enabled This rule detects Application Gateways that do not have WAF enabled, logging findings and providing remediation steps. * feat: add rule AZ-NET-008 — load balancer with no backend pool This rule detects load balancers in Azure that are not configured with a backend pool, indicating potential misconfiguration or unnecessary costs. * feat: add rule AZ-NET-009 — VPN gateway using outdated IKE version This script detects VPN gateways using the outdated IKEv1 protocol and provides remediation steps to migrate to IKEv2. * feat: add rule AZ-NET-010 — subnet with no NSG attached This script detects subnets in Azure that do not have a Network Security Group (NSG) attached, logging findings and providing remediation guidance. * feat: add playbook fix_az_net_003.sh This script updates the NSG rule to restrict inbound traffic on port 443 to a specified IP range. * feat: add playbook fix_az_net_004.sh This script adds a default deny-all inbound rule to a specified NSG. * feat: add playbook fix_az_net_005.sh This script enables DDoS protection on a specified virtual network in Azure. It checks for required parameters and provides usage instructions if they are missing. * feat: add playbook fix_az_net_006.sh This script deletes unassociated public IP addresses in Azure. * feat: add playbook fix_az_net_007.sh This script enables WAF on an Application Gateway, ensuring compliance with the AZ-NET-007 rule. * feat: add playbook fix_az_net_008.sh Script to remediate AZ-NET-008 by deleting empty load balancers. * feat:add script to update VPN connection to IKEv2 This script updates a VPN connection to use IKEv2, ensuring compliance with the AZ-NET-009 rule. * feat: add playbook fix_az_net_010.sh This script attaches a specified network security group to a given subnet in a virtual network, ensuring compliance with the AZ-NET-010 rule. * Clarify description and add note for public-facing services Updated the description to clarify the risk of exposing port 443 and added a note regarding public-facing services. * Change severity level from MEDIUM to HIGH * fix: AZ-NET-005 severity changed to LOW — DDoS Standard high cost on small subscriptions * Add note about NetworkManagementClient usage Added a note regarding the creation of NetworkManagementClient directly and suggested a follow-up for consistency. * Add note about NetworkManagementClient usage Added a note regarding the use of NetworkManagementClient and suggested a follow-up for consistency. * Add additional security controls to CIS Azure benchmark * Refine control descriptions in nist_csf.json Updated descriptions for various controls to enhance clarity and specificity regarding remote access management, data protection, and security measures. * fix: add AZ-NET-003 to AZ-NET-010 to ISO27001 compliance framework Updated descriptions for various controls to clarify compliance requirements and improve security guidance. --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> * Feat/az stor 003 (#21) * feat: add rule AZ-STOR-003 storage lifecycle policy check * feat: add rule AZ-STOR-003 storage lifecycle policy check * docs: add SOC 2 Type II compliance framework mapping (#33) * docs: add SOC 2 Type II compliance framework mapping for all 20 rules Added SOC 2 Type II framework with detailed controls for security measures and compliance requirements. * feat: add soc2 to FRAMEWORK_FILE_MAP in finding.py add soc2.json to FRAMEWORK_FILE_MAP in finding.py * feat: add soc2 to SUPPORTED_FRAMEWORKS in compliance.py Added 'soc2' to the list of supported compliance frameworks. * Add SOC 2 controls for data protection and management * Refactor/azure client network methods (#22) * refactor: add get_virtual_networks() and get_public_ip_addresses() to AzureClient * Refactor DDoS protection check to use azure_client * refactor: AZ-NET-006 now uses azure_client.get_public_ip_addresses() * feat: add CI pipeline with 6 automated checks (#34) - Python syntax check on all rule files - Rule structure validation (RULE_ID, SEVERITY, FRAMEWORKS) + RULE_ID uniqueness - Hardcoded credential scan - Playbook existence + bash syntax check for every rule - Compliance JSON validation for all four framework files (inc. soc2.json) - API syntax check - Compliance vs rule cross-reference check - CI summary step with per-check pass/fail table (if: always) - Fix duplicate DESCRIPTION assignment in az_net_003.py - Add pyyaml to requirements.txt for local YAML validation - Add docs/ci-pipeline.md with local run commands and design rationale - Update CI_PIPELINE_GUIDE.md with final PR description Closes #30 * docs: update .github/ISSUE_TEMPLATE/new_rule.md to reflect current codebase state * docs: update .github/PULL_REQUEST_TEMPLATE.md to reflect current codebase state * docs: update CONTRIBUTING.md to reflect current codebase state * docs: update README.md to reflect current codebase state * docs: update compliance/frameworks/iso27001.json to reflect current codebase state * docs: update compliance/frameworks/nist_csf.json to reflect current codebase state * docs: update docs/adding-a-rule.md to reflect current codebase state * docs: update docs/architecture.md to reflect current codebase state * docs: update docs/az-stor-003-test-plan.md to reflect current codebase state * docs: update docs/azure-setup.md to reflect current codebase state * docs: update docs/ci-pipeline.md to reflect current codebase state * docs: update docs/sentinel-setup.md to reflect current codebase state * docs: update sentinel/TEST_PLAN.md to reflect current codebase state * docs: update docs/api-reference.md to reflect current codebase state * docs: update docs/rules-reference.md to reflect current codebase state * docs: update README.md for professional open source style * docs: update CONTRIBUTING.md for professional open source style * docs: update docs/adding-a-rule.md for professional open source style * docs: update deployment guide to use Render instead of Azure App Service * feat: add rule AZ-STOR-004 storage account diagnostic logging check (#39) * feat: add rule AZ-STOR-004 storage account diagnostic logging check Detects Azure storage accounts where diagnostic logging is not fully enabled on blob, queue, or table services. Emits one finding per non-compliant service (StorageRead, StorageWrite, StorageDelete must all be enabled). Adds get_storage_service_logging() to AzureClient using MonitorManagementClient. Includes remediation playbook that enables all three services in one run. Frameworks: CIS 3.3, NIST DE.CM-7, ISO 27001 A.12.4.1 * chore: add AZ-STOR-004 compliance mappings --------- Co-authored-by: Shaurya K Sharma * feat: add rule AZ-IDN-003 Adds scanner rule AZ-IDN-003 detecting Entra ID (#48) * feat: add scanner rule AZ-IDN-003 — guest user invitations not restricted to admins * feat: add remediation playbook fix_az_idn_003.sh This script restricts guest user invitations to only admins and users with the Guest Inviter role in Azure Active Directory. * feat: add AZ-IDN-003 to CIS compliance framework Added control for guest invite restrictions to enhance security. * feat: add AZ-IDN-003 to NIST compliance framework * feat: add AZ-IDN-003 to ISO27001 compliance framework Added control AZ-IDN-003 for user registration and de-registration process. * feat: add AZ-IDN-003 to SOC2 compliance framework * feat: add rule AZ-CMP-002 — VM disk not protected by CMK or ADE (#47) * feat: add scanner rule AZ-CMP-002 — VM disk not protected by CMK or ADE This script detects virtual machines whose disks use platform-managed encryption only and provides findings for compliance with CIS 7.2. * feat: add remediation playbook fix_az_cmp_002.sh This script enables Azure Disk Encryption on a specified virtual machine using a Key Vault for the disk encryption key. * feat: add AZ-CMP-002 to CIS compliance framework Added a new control for OS disk encryption requirements. * feat: add AZ-CMP-002 to NIST compliance framework * feat: add AZ-CMP-002 to ISO27001 compliance framework Added control AZ-CMP-002 regarding cryptographic controls policy and its requirements. * feat: add AZ-CMP-002 to SOC2 compliance framework * fix: correct indentation in CIS AZ-CMP-002 entry * feat: add remediation playbook fix_az_cmp_002.sh to correct location This script enables Azure Disk Encryption on a specified virtual machine using a provided Key Vault for disk encryption. * Delete fix_az_cmp_002.sh * Feat/api deployment (#46) * feat: deploy API to Render with security hardening and CI/CD optimizations * feat: finalize Render deployment with security hardening and Gunicorn import fix * fix: GitHub Actions syntax and secret detection logic in deploy workflow * ix: harden scan trigger route with detailed error handling and remove redundant DB initialization * fix: implement global database connection management and harden all API routes * ix: prevent insecure smoke tests on main branch by enforcing JWT_SECRET presence and prevent CI false negatives in playbook check by enforcing non-empty glob match * fix: resolve Render startup crash and harden scan serialization against recursive objects * fix: add missing six and cryptography dependencies for Azure SDK compatibility * fix: increase CI wait time for Render build and add missing msrest dependencies * feat: integrate real subscription ID into smoke tests and CI/CD pipeline * feat: integrate real Azure_ ID's into smoke tests and CI/CD pipeline * feat: add root welcome route to confirm API status * fix: resolve specific CI credential flags in code and workflow while maintaining documentation standards * fix: resolve IndentationError in CI compliance cross-reference check * fix: resolve dependency issue and test on deployment * fix: resolve somke test TC-21 * fix: RUN_REAL_SCAN not set → TC-13/TC-14 skip → 21/21 pass for new live API url test * fix: scan.py deferred import from scanner.engine import ScanEngine was running before the subscription_id check * fix: restrict deploy triggers to dev and main, enable RUN_REAL_SCAN for maintainer CI, and update test plan documentation * feat: AZ-NET-011 Network Watcher not enabled in all regions (#42) * feat: add AZ-NET-011 Network Watcher rule, playbook and compliance mappings * fix: add missing AzureClient methods, SOC2 mapping and fix playbook region * fix: add SOC2 CC7.2 to FRAMEWORKS in az_net_011.py * feat: add AZ-DB-003 PostgreSQL Flexible Server SSL enforcement rule a… (#49) * feat: add AZ-DB-003 PostgreSQL Flexible Server SSL enforcement rule and playbook * fix: correct requirements.txt formatting for postgresqlflexibleserver * fix: correct postgresqlflexibleservers package name and version * fix: handle empty params gracefully and clean up playbook output --------- Co-authored-by: Tanvir Farhad Co-authored-by: PARTH J ROHIT Co-authored-by: Ritik Sah Co-authored-by: Shaurya K Sharma Co-authored-by: Shaurya K Sharma Co-authored-by: Mahfuzur Rahman Emon * refactor: reuse database connection per request using Flask g (#41) * fix: improve scan routes error handling and database reuse * fix: add database connection reuse and DATABASE_URL validation to score.py * fix: add database connection reuse, DATABASE_URL validation, and FileNotFoundError handling to compliance.py * fix: enforce JWT_SECRET environment variable, remove hardcoded default * ci: trigger fresh CI run * fix: all requirements - g.db naming, teardown, close() method * fix: update az_net_012.py to match az_cmp_003 pattern and add set -euo pipefail to bash script * fix: correct az_net_012.py signature, add set -euo pipefail, add AZ-NET-012 to all compliance files * fix: correct az_net_012.py to match az_cmp_003 pattern --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> Co-authored-by: Tanvir Farhad Co-authored-by: PARTH J ROHIT Co-authored-by: Ritik Sah Co-authored-by: Shaurya K Sharma Co-authored-by: Shaurya K Sharma Co-authored-by: Mahfuzur Rahman Emon * fix: resolve CodeQL warnings in embed.py and test files * feat(frontend): build complete 7-page security dashboard (#111) * Basic components and pages with dummy data * feat(frontend): build complete 7-page security dashboard Complete React 18 + Vite frontend for OpenShield security platform. Pages (7): - Monitoring — security score gauge, trend chart, findings distribution, issues by resource group, category scores - Discovery — resource table with issue counts, risk filters, category grouping, resource group filtering, clickable category cards - Prioritization — risk vs effort matrix, ranked list with quick remediation preview, all 25 action items; click-to-select syncs matrix + action items + remediation panel - Detailed Scan — findings list with playbook tabs (portal/CLI/validation), navigates from Prioritization with context banner - Compliance — CIS/NIST/ISO27001/SOC2 framework cards, controls table, comparison trend chart, CSV/JSON export - Drift — configuration change timeline, ADDED/REMOVED/MODIFIED events with before/after values, who changed it and when - AI Assistant — 3-column layout (findings picker, chat, suggestions + CVE analysis + executive summary); AI chat wired to aiApi.js with smart mock responses; finding context passed from Scan page API service layer (src/utils/api.js): - Demo/Live mode toggle persisted in localStorage - JWT token bootstrap in App.jsx - Health check on startup with auto-fallback to demo mode - Real fetch calls with mock fallback for every endpoint: /api/score, /api/findings, /api/findings/:id, /api/findings/:id/playbook, /api/resources, /api/prioritization, /api/drift, /api/scans, /api/scans/trigger, /api/scans/:id, /api/compliance/cis|nist|iso27001 - snake_case → camelCase normalisation for all backend responses - Separate aiApi.js for AI endpoints with smart mock responses Header features: - Run Scan button with live polling (4s interval, 5-min timeout, elapsed timer) - Demo/Live badge with connection test before switching - Error popup if backend is unreachable Design system: - Tailwind CSS v3 with custom tokens (brand, severity, bg-dark, status) - Dark mode via class strategy, persisted in localStorage - Fully responsive — mobile hamburger drawer, stacked layouts on sm - Dot-pattern background, soft shadows, consistent 4px grid Mock data: - 8 api.*.json files matching exact backend response schema - API_ENDPOINTS.txt — backend contract document with implementation status, database schema, seed data, and endpoint ordering guide Co-Authored-By: Claude Sonnet 4.6 * feat(frontend): wire live backend, fix JWT auth, add Vercel deployment config - Fix JWT: read VITE_JWT_TOKEN env var so live API calls authenticate correctly (was sending plain string 'dev-demo-token' which backend rejected as invalid JWT) - Add vercel.json with SPA rewrites so /monitoring, /scan etc don't 404 - Monitoring page now fetches real score + findings in live mode and computes stats/distribution/resource-group breakdown from actual backend data - Run Scan button shows subscription ID input in live mode (optional — backend falls back to AZURE_SUBSCRIPTION_ID env var if blank) - api.js: no silent localhost fallback in production builds (fails loudly if VITE_API_URL is not set) --------- Co-authored-by: Claude Sonnet 4.6 * Feat/jwt secret prod fail closed (#117) * fix: smoke test aligned after recent codebase changes * feat: fail closed on insecure JWT_SECRET in production * fix: rename _DEFAULT_JWT_SECRET to avoid CI credential scanner false positive * feat: AI-004 RAG Pipeline - Document Ingestion and Vector Store (#104) * feat: add AZ-IDN-004 PIM not configured for admin roles rule and playbook * feat: add RAG pipeline with document loader, chunker, embedder, ChromaDB vector store and Flask API routes * fix: remove duplicate ai files, restore deleted compliance rules, revert requirements to chromadb 0.4.24 * fix: update gitignore to use ai/vectorstore/ and clean up README references * fix: add missing newline at EOF in compliance JSON files * Potential fix for pull request finding 'Unused import' Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> * feat: add PQC compliance mappings, azure client methods and dependencies --------- Co-authored-by: Tanvir Farhad Co-authored-by: PARTH J ROHIT Co-authored-by: Ritik Sah Co-authored-by: Shaurya K Sharma Co-authored-by: Shaurya K Sharma Co-authored-by: Mahfuzur Rahman Emon Co-authored-by: Safid Nadaf <137755124+safidnadaf@users.noreply.github.com> Co-authored-by: Abdulbosit Abdurazzakov <2d9c6kh58x@privaterelay.appleid.com> Co-authored-by: Mahfuzur Rahman Emon Co-authored-by: Prayas Gautam <159550781+vogonPrayas@users.noreply.github.com> Co-authored-by: Claude Sonnet 4.6 Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> * docs: update OpenShield Learn portal * docs: update OpenShield Learn portal * docs: redirect Learn site root * docs: add OpenShield Learn link to README * docs: update OpenShield Learn portal --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> Co-authored-by: Tanvir Farhad Co-authored-by: Ritik Sah Co-authored-by: Shaurya K Sharma Co-authored-by: Shaurya K Sharma Co-authored-by: Mahfuzur Rahman Emon Co-authored-by: Safid Nadaf <137755124+safidnadaf@users.noreply.github.com> Co-authored-by: Abdulbosit Abdurazzakov <2d9c6kh58x@privaterelay.appleid.com> Co-authored-by: Mahfuzur Rahman Emon Co-authored-by: Prayas Gautam <159550781+vogonPrayas@users.noreply.github.com> Co-authored-by: Claude Sonnet 4.6 Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> * feat(tests): MockAzureClient rule regression test harness — 7 rules offline (#124) * feat: initialise tests/helpers package * feat: add MockAzureClient test helper Introduced MockAzureClient for offline testing of Azure-related functionality. * feat: add mock_azure and subscription_id fixtures to conftest Add fixtures for mock Azure client and subscription ID * feat: add storage rule regression tests for AZ-STOR-001 and AZ-STOR-002 This file contains regression tests for storage rules AZ-STOR-001 and AZ-STOR-002, ensuring compliance checks for public access and HTTPS-only settings. * feat: add network rule regression tests for AZ-NET-001 and AZ-NET-002 Add regression tests for AZ-NET-001 and AZ-NET-002 rules to validate compliance and non-compliance scenarios for NSGs. * feat: add identity rule regression tests for AZ-IDN-001 Added regression tests for AZ-IDN-001 rule to validate compliance and non-compliance scenarios. * feat: add key vault rule regression tests for AZ-KV-002 Added regression tests for AZ-KV-002 rule to validate Key Vault compliance based on public access and private endpoint configurations. * feat: add database rule regression tests for AZ-DB-004 Add regression tests for AZ-DB-004 rule compliance. * Add pytest dependencies and rule regression test CI step * Add rule regression tests to CI workflow * Add DATABASE_URL environment variable for tests * Refactor imports and update JWT handling in tests * Remove unused jwt import from conftest.py * Enhance comments for hardcoded credential scan Added comments to clarify credential scanning patterns. * AZ-IDN-005 to AZ-IDN-009 — Entra ID identity scanner rules (#109) * Add AZ-IDN-005 rule for guest user role detection This script detects guest users assigned to high privilege roles in Entra ID and logs findings for remediation. * Add AZ-IDN-006 rule for client secret expiry check Implement AZ-IDN-006 rule to detect service principal client secrets older than 90 days or without expiry. The rule includes logging, fetching applications from Graph API, and evaluating credentials. * Add AZ-IDN-007 rule for MFA registration detection This rule detects active user accounts in Entra ID that do not have multi-factor authentication methods registered, highlighting potential security vulnerabilities. * Add AZ-IDN-008 rule for RBAC role scanning This script detects custom RBAC roles with wildcard or overly broad permissions at the subscription scope and provides remediation steps. * Add AZ-IDN-009 rule for role assignment alerts This rule checks for the absence of activity log alerts for role assignment changes in Azure subscriptions, logging findings if no alerts are configured. * Add remediation playbook for AZ-IDN-005 This script provides a remediation playbook for removing high privilege roles from guest users in Entra ID, including usage instructions and role assignment fetching. * Add remediation playbook for AZ-IDN-006 This script provides a remediation playbook for rotating service principal client secrets older than 90 days. It includes usage instructions and steps for listing, resetting credentials, and migrating to managed identities. * Add MFA enforcement remediation playbook script This script provides a remediation playbook for enforcing MFA registration for users without MFA in Entra ID. It includes steps to identify users and create a Conditional Access policy. * Add remediation playbook for AZ-IDN-008 This script provides a playbook for remediating custom RBAC roles with wildcard permissions at the subscription scope, guiding users through listing, reviewing, and updating roles. * Add script to create activity log alert for role changes This script creates an activity log alert for role assignment changes to detect privilege escalation in real time. * Add new controls for Azure security compliance * Add new NIST CSF controls for identity and access management * Add ISO 27001 controls for security compliance Added new controls for privileged access management, password management, secure log-on procedures, and event logging to comply with ISO 27001 standards. * Add SOC 2 controls for logical access and monitoring * Potential fix for pull request finding 'Empty except' The fix is right! Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> * Potential fix for pull request finding 'Unused variable, import, function or class' Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> * Implement threat simulation prompt builder (#138) Add a function to build a threat simulation prompt based on findings and context. * docs: add frontend API validation guide (#134) Co-authored-by: Shaurya K Sharma * fix(compliance): align rule reference and framework mappings (#130) * feat: implement asynchronous scan execution with background worker (#129) * feat: implement asynchronous scan execution with background worker * chore: async scan architecture with 100% verified test suite * feat: complete transition to async scan architecture with verified E2E suite and docs * fix: addressed the requested changes * fix: address security and architecture issues in async scan processing - Sanitize worker error messages to prevent sensitive exception details from being exposed through the public API - Revert unrelated schema and search_path changes to maintain compatibility with existing public-schema deployments - Add column to preserve as the original queue timestamp - Improve migration logic to correctly backfill historical scans and repair incorrect statuses - Update worker tests to reflect generic error handling and the new atomic scan-claiming workflow * feat(scanner): add AZ-NET-015 public DNS zone enumeration rule (#106) * feat(scanner): add AZ-NET-015 public DNS zone enumeration rule - Add scanner/rules/az_net_015.py to detect public DNS zones - Add get_dns_zones() to azure_client.py using DnsManagementClient - Add playbooks/cli/fix_az_net_015.sh remediation script - Add azure-mgmt-dns==8.0.0 to requirements.txt - Update all 4 compliance framework JSONs with AZ-NET-015 mappings * feat(scanner): add get_dns_record_sets to AzureClient * feat(scanner): rewrite AZ-NET-015 to detect RFC1918 IPs and internal hostnames in public DNS zones * feat(compliance): add AZ-NET-015 mappings to all four framework JSON files * fix: scope posture endpoints to latest completed scan (#145) * Update finding.py total_findings > 0 skips any scan where 0 issues were found. So after you fix all misconfigs and run a clean scan, the dashboard ignores it and keeps showing the old dirty scan. status = 'completed' picks the latest scan that finished successfully, whether it found 0 things or 100 things. * Update finding.py * Update ci.yml * Create test_clean_scan.py all confirmed passing locally. Zero real DB or Azure calls pure mock. * Update ci.yml * Update finding.py * Fix: Make Flask app test-safe and run full pytest suite in CI (#143) * fix: skip DB migrations when DATABASE_URL is unset and add full pytest step to CI * fix: add PYTEST to CI Summary env section * feat: Integrate Azure Offensive Skills and Dynamic AI Grounding (#137) * feat: integrate azure offensive skills with dynamic grounding and metadata standardization * feat(ai): harden RAG grounding logic and stabilize vectorstore rebuild flow * fix(ci): decouple app from database during test collection and execution * fix(ci): prevent side-effect create_app() call during pytest collection * fix(tests): mock database manager in jwt config integration tests --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> * feat(auth): require JWT for GET /api/* endpoints with optional public demo mode (#144) * Update public access paths and database migration logic Refactor public access logic and improve database migration handling. * Add tests for JWT authentication middleware This file contains tests for JWT authentication middleware, including both production and demo modes. It tests various endpoints for JWT requirements and public access. * Enhance API reference with authentication details Added authentication details and public demo mode information to the API reference. * Add auth tests to regression test suite * Remove DATABASE_URL from CI workflow Removed DATABASE_URL environment variable from rule regression tests. * Update ci.yml * fix: mock DatabaseManager in test_auth.py fixtures to prevent CI DB connection * fix(scanner): improve AZ-NET-008 with SOC2 mapping and azure_client abstraction (#108) * CI: parallel jobs, lint/format gate, security scanning, coverage (#155, #156) (#165) * ci: parallel CI jobs with lint, security scanning, coverage and branch-flow gates (#155, #156) * ci: attach SBOM to releases, pin CI node to 22, harden release workflow (#156) * Fix async scan state recovery (#169) * feat(infra): observability layer — structured logs, request IDs, metrics, readiness probe (#167) Implements issue #159 (INFRA 6). - api/observability.py: shared module with JSON logging (python-json-logger), optional Sentry init (only when SENTRY_DSN set), request-ID middleware, Prometheus metrics, and the /metrics endpoint. - api/app.py: wire observability middleware first; split /health (liveness, no DB) from /ready (DB connectivity → 200/503); echo X-Request-ID; include request_id in JSON error responses and auth failures; /ready + /metrics public. - api/models/finding.py: add DatabaseManager.ping() for the readiness probe. - scanner/worker.py: shared JSON logging, conditional Sentry, scan_id as a structured log field, scan success/failure counters, scan duration, queue depth. - scanner/engine.py: increment per-rule error counter when a rule raises. - scanner/nvd_client.py, api/services/ai_provider.py: record external-call latency. - requirements.txt: add prometheus-client, python-json-logger, sentry-sdk. - tests/test_observability.py: probes, /metrics, request IDs, auth request_id, conditional Sentry, worker metrics. No metric is labelled with request_id, scan_id, subscription_id, resource_id, error_message or user input. Co-authored-by: Shaurya K Sharma * fix(compliance): correct duplicate CIS control mappings, TLS version compare, Graph pagination (#166) * fix(compliance): correct duplicate CIS control mappings, TLS version compare, Graph pagination - Fix AZ-CMP-001 sharing CIS control 7.2 with unrelated AZ-CMP-002 - De-duplicate 13 rules that shared CIS control_id values across cis_azure_benchmark.json, their rule files, docs, and the website - Replace lexicographic TLS version comparison in az_pqc_001 with a numeric parser so "1.10" is no longer misread as below "1.3" - Follow @odata.nextLink pagination in get_conditional_access_policies instead of dropping all results past the first page * style: apply ruff format to new compliance/pagination tests * build(deps): bump react-router (#148) Bumps the npm_and_yarn group with 1 update in the / directory: [react-router](https://github.com/remix-run/react-router/tree/HEAD/packages/react-router). Updates `react-router` from 7.15.0 to 7.18.0 - [Release notes](https://github.com/remix-run/react-router/releases) - [Changelog](https://github.com/remix-run/react-router/blob/main/packages/react-router/CHANGELOG.md) - [Commits](https://github.com/remix-run/react-router/commits/react-router@7.18.0/packages/react-router) --- updated-dependencies: - dependency-name: react-router dependency-version: 7.18.0 dependency-type: indirect dependency-group: npm_and_yarn ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * build(deps-dev): bump vite (#147) Bumps the npm_and_yarn group with 1 update in the /frontend directory: [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite). Updates `vite` from 8.0.14 to 8.0.16 - [Release notes](https://github.com/vitejs/vite/releases) - [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite/commits/v8.0.16/packages/vite) --- updated-dependencies: - dependency-name: vite dependency-version: 8.0.16 dependency-type: direct:development dependency-group: npm_and_yarn ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * docs: add Azure scanner validation docs (#142) * fix: disable auto deploy to Render, manual trigger only * fix: ruff auto fixes * fix: resolve CodeQL high findings - XSS innerHTML, clear text logging and key storage * chore: add CODEOWNERS, issue templates, Docker setup and autonomous CI workflows * fix: raise dependency review threshold to critical only * fix: upgrade vulnerable dependencies flagged by pip-audit and npm audit * fix: revert dependency review threshold back to high * fix: use python:3.11-slim-bookworm base image to reduce Trivy vulnerabilities * fix: upgrade jaraco.context, transformers and wheel to fix Trivy HIGH findings * feat(db): implement Alembic migrations (#164) * feat(db): implement Alembic migrations (#158) * ci: validate Alembic migrations in backend tests * fix: remediate container scan vulnerabilities (#175) * Reliability fixes: score 500, DB pooling, async CVE enrichment, thread-safe rate limit (#162) * fix(reliability): score endpoint 500, DB pooling, async CVE enrichment, thread-safe rate limit Closes #150. - REL-001: remove duplicate GROUP BY in get_score() that made /api/score always return 500 - REL-002: replace fragile INTERVAL '%s minutes' string substitution with make_interval(mins => %s) - REL-003: DatabaseManager now borrows connections from a shared psycopg2 connection pool per DSN (DB_POOL_MAX_CONN, default 10) instead of opening a new connection per request - REL-004: POST /api/scans//enrich now runs CVE enrichment in a background thread and returns 202 immediately, instead of blocking on synchronous NVD lookups until the request times out - REL-005: lock-guard the NVD client's rate-limit check so concurrent callers can't fire requests closer together than the allowed gap - Fix a bug found during review: a failed enrichment write could leave the connection in an aborted-transaction state, silently swallowing the follow-up FAILED status update and leaving the scan stuck at ENRICHING forever; now rolls back first * fix(tests): consolidate duplicate module import style flagged by code-quality bot Both test_database_manager_reliability.py and test_nvd_client.py imported scanner/api modules with both 'import X as x' and 'from X import y' forms. Consolidated to one form each; test_nvd_client.py switches to string-path mock.patch() targets instead of importing the module object, avoiding the need to touch ~15 pre-existing call sites. * fix(scanner): encapsulate NVD rate limiter state to resolve unused-global false positive Replaces the bare module-level _last_request_time global (mutated via the global keyword) with a small _RateLimiter class holding the timestamp and lock as instance state. Same behavior, but removes the pattern the code-quality bot's static analysis was misreading as an unused global (it couldn't see the value is read by the next invocation of the same function via module state). * style: apply ruff format to satisfy new CI lint gate * fix(reliability): restore attempt-count check in recover_stale_scans The "mark failed" query lost its COALESCE(attempt_count, 1) >= %s clause during an earlier merge, while still passing 2 params to a query with only 1 placeholder — this would raise at runtime against a real database and would mark stale scans failed on their first timeout instead of after max_attempts retries. Restore the clause to match the tested, correct version. Also drop the now-superseded REL-002 test, whose single-query assumptions predate the retry-attempt feature; equivalent coverage now lives in tests/test_async_scan_persistence.py. * fix: remove dead run_migrations() call from create_app() A previous merge auto-resolved cleanly across files but left this call site stranded: api/models/finding.py dropped run_migrations() (schema is now Alembic-managed, applied via startup.sh) while api/app.py still called it whenever DATABASE_URL was set. Git's merge saw no conflict because the removal and the call site were in different files, but the result crashed create_app() with AttributeError in any environment with a real DATABASE_URL configured (e.g. CI's Postgres service), which is exactly why this passed locally (no DATABASE_URL set) but failed in CI. * test: add comprehensive validation coverage (#146) * test: add scanner rule and engine validation coverage Expand scanner rule regression coverage so all 45 rules have dedicated compliant and non-compliant cases (includes az_net_015). Add ScanEngine integration tests for rule loading, score consistency, and rule-failure isolation. Extend MockAzureClient test support only; no production code is changed. Full suite: 170 passed. Rule regression slice: 92 passed. Engine integration: 4 passed. Note: AZ-NET-009 and AZ-NET-012 tests validate intended isolated rule logic. The production integration defects discovered during validation are documented separately in the validation report. * docs: add comprehensive validation report Document the full OpenShield validation pass across environment setup, static checks, backend tests, scanner rules, engine integration, local API smoke tests, frontend build, AI/RAG, CVE/NVD, Sentinel review, security checks, documentation accuracy, and live deployment status. The report records remaining follow-up issues including AZ-NET-009, AZ-NET-012, AI chunker syntax failure, Sentinel field mapping mismatch, stale documentation counts, dependency CVEs, and deferred Azure/Sentinel live validation. * test: relax engine rule-count assertions to >= 45 Future rule additions should not break the engine integration tests. Assert at least the current 45-rule coverage exists rather than the exact total (addresses reviewer feedback). * test: finalize validation coverage for merge * test: apply ruff format and line-length fixes to validation tests * infra 7 : Terraform for Render/Vercel + GitHub OIDC for Azure credentials (#176) * docs: add design spec for Terraform IaC + Azure OIDC (issue #160) * docs: add implementation plan for Terraform IaC + Azure OIDC (issue #160) * infra: add Terraform provider/backend skeleton for Render and Vercel * infra: define Render Postgres, web service, and shared secrets env group * infra: define Vercel projects for the dashboard and website * infra: add Terraform outputs and module README * ci: add Terraform fmt/validate/plan workflow for infra PRs * ci: authenticate to Azure via OIDC instead of a long-lived client secret * docs: document one-time Azure AD federated credential setup for OIDC * docs: update secrets table for OIDC, add secrets inventory doc * Security hardening: body size limit, Gemini key header, AI rate limiting, playbook path traversal (#161) * fix(security): body size limit, Gemini key in header, AI rate limiting, playbook path traversal guard Closes #149. - SEC-002: cap request bodies at 2MB with a JSON 413 handler - SEC-003: send the Gemini API key via x-goog-api-key header instead of a URL query param, so it never leaks into logs - SEC-004: add a lightweight in-memory rate limiter (20 req/min/IP) on all AI endpoints - SEC-005: validate rule_id and confirm the resolved script path stays inside playbooks/cli/ before reading it - SEC-001 was already fixed on dev via #144; added a regression test to lock it in * fix(security): back rate limiter with Postgres, trust Render's proxy hop for client IP - Merge latest dev (ruff lint/format CI gate) and reformat the one flagged file - Replace the in-memory rate limiter with a Postgres-backed shared counter (rate_limit_hits table + advisory transaction lock) so all gunicorn worker processes enforce one real limit instead of each having its own counter - Add ProxyFix so request.remote_addr reflects the real client behind Render's reverse proxy instead of collapsing every caller into one IP - Reuse the existing g.db connection instead of a second untracked one, so it's closed by the app's existing teardown handler instead of leaking - Refuse (503) instead of silently and permanently disabling rate limiting when DATABASE_URL is unset, and roll back on a mid-transaction error * fix(tests): use single import style for api.rate_limit * Infra: add deterministic Render deploy pipeline and separate worker services (#172) * infra: add deterministic Render deploy pipeline * infra: make Render deploy workflow manual * fix(deploy): coordinate API and worker releases * fix(deploy): add resilient Render polling * test(deploy): cover coordinated deployment failures * docs(deploy): document dual-service Render releases * fix(deploy): avoid logging dispatch input * fix(deploy): correct rollback path and Render web configuration * docs(deploy): retire obsolete Render deployment guide --------- Co-authored-by: Vishnu Ajith <86302373+Vishnu2707@users.noreply.github.com> * fix(security): drop credential key_id from AZ-IDN-006 debug logging (#184) app_id/key_id are Azure AD identifiers, not the secret value itself (Microsoft Graph never returns password credential secret text after creation) — but key_id isn't needed to diagnose a malformed endDateTime either way, so drop it from the log line rather than argue the classification. Fixes #178 (CodeQL: clear-text logging of sensitive information, both findings — same log statement). * fix(security): resolve all high/critical CodeQL findings (#177, #179, #180) (#183) * fix(security): validate embed URLs by origin instead of substring match toEmbedUrl()'s fallback branch used raw.includes(...) to check for a known-safe embed URL, then returned the unvalidated input unmodified. A crafted string containing the substring anywhere could pass the check while breaking out of the iframe's src="..." attribute it gets interpolated into unescaped, injecting arbitrary markup. Validate via new URL(raw).hostname against an exact allowlist instead, and escape the result at every interpolation site as defense in depth. Also escape the two playground select-field values that were concatenated into an HTML-shaped string unescaped. Fixes #179 (CodeQL: DOM text reinterpreted as HTML x3, incomplete URL substring sanitization x1). * fix(security): move AI provider API key to in-memory-only storage A prior fix for this same CodeQL alert removed the localStorage.setItem call for the user's bring-your-own AI provider key but left the getter/isConfigured() reading from the now-permanently-empty key, silently breaking every AI feature (chat, summary, insights, prioritisation all gated behind isConfigured()). Store the key in a module-scoped variable instead of any browser storage. It never survives a page reload (the standard, expected trade-off for a secret that must not persist), but the feature works again and the key is never written to localStorage/sessionStorage. provider/model (not secret) still persist in localStorage as before. Fixes #180 (CodeQL: clear text storage of sensitive information). * fix(security): stop leaking exception details in API error responses Every affected route returned str(exc) (or an f-string embedding it) directly in the JSON response body. Some catch broad `except Exception`, which can surface raw database driver errors, connection details, or internal paths to the client rather than just intentional validation messages. Replace with a fixed, generic message per error class; the existing logger.error(...)/logger.warning(...) calls already capture full detail server-side. In api/routes/ai.py, extract a shared _ai_error_response() helper since the same 3-exception pattern (VectorStoreNotBuilt, ValueError, RuntimeError from get_completion()) repeated verbatim across 4 routes, and add the server-side logging that was missing there entirely. Also fixes an f-string leak in compliance.py's FileNotFoundError handler that the "detail" key search missed. Fixes #177 (CodeQL: information exposure through an exception, all 27 findings across api/app.py and 8 api/routes/ modules). * fix: remove escapeHTML() misapplied to .textContent sinks Self-review caught that the defense-in-depth escapeHTML() calls added for #179 wrapped values assigned via .textContent, not .innerHTML. .textContent never interprets HTML, so escaping there adds no security value while risking visible text corruption (a literal "&" shown on screen) if the underlying value ever contains a special character. toEmbedUrl()'s URL-origin validation is the real, load-bearing fix and is unaffected by this change — it guarantees embedUrl can only ever be '' or a well-formed https://youtube.com|vimeo.com URL regardless of which DOM property ultimately consumes it. * fix(security): resolve Semgrep SAST findings (#185) * fix(security): harden workflow shell execution Route deployment inputs through environment variables and replace remote installer pipes with checksum-verified Syft archives. Consolidate workflow permissions so deployment validation can run. Addresses #182. * fix(security): resolve remaining Semgrep findings Pin workflow and browser dependencies, remove unsafe evaluation and dynamic query construction, enforce trusted network destinations, harden local containers, and prevent sensitive JWT error logging. Fixes #182. * style(security): format endpoint validation * fix(security): preserve validated URL suppression * feat(pqc): add CBOM endpoint, quantum risk scoring, NCSC and ENISA framework mappings, HNDL exposure window and migration roadmap (#187) Signed-off-by: Vishnu Ajith <27vishnu07@gmail.com> * feat(scanner): add enterprise AKS security rule pack (#189) * feat(scanner): add enterprise AKS security rule pack * style(scanner): format AKS rules * ci: document AKS SDK license exception * fix(security): complete #183 XSS and legacy AI key follow-up (#188) Two residual issues from #183's merge, found in post-merge review: - toEmbedUrl() validated the host via new URL() but returned the raw input, so an attribute-injection payload on an allowed host (e.g. https://www.youtube.com/embed/abc" onload="alert(1)) passed validation and kept its literal double-quote, breaking out of the iframe src="..." attribute. Now returns parsed.href, which percent-encodes quotes, spaces, and brackets. - The switch to in-memory key storage removed the localStorage write but never purged keys that older builds had already stored, so existing users kept a plaintext ai_api_key indefinitely. Added a one-time purge on module load (not read into memory) and in clear(). Both fixes ship with regression tests confirmed to fail against the pre-fix code and pass against the fix. Co-authored-by: Claude Fable 5 * docs: add CHANGELOG, API reference, coding standards and OpenSSF gold badge compliance (#190) * docs: add OpenSSF Passing badge (#192) * Add Semgrep SAST to CI alongside CodeQL (#210) * Add Semgrep SAST to CI alongside CodeQL * Add non-root USER to Dockerfile to satisfy Semgrep gate * Document Dockerfile hardening intent and Semgrep registry dependency * Remove issue reference from Dockerfile comment * docs: prepare OpenSSF Silver readiness evidence (#200) * fix(scanner): resolve COR-001-004 scanner correctness issues (#151) (#163) * fix(scanner): resolve COR-001-004 scanner correctness issues (#151) * fix(scanner): normalise Azure SDK enum fields in AZ-NET-003 and AZ-DB-002 Addresses review feedback on PR #163: - Add a shared enum_str() helper in azure_client.py that safely unwraps Azure SDK enum fields via .value, since str(enum_member) yields e.g. 'SecurityRuleDirection.INBOUND' rather than 'Inbound' and silently breaks naive string comparisons against real SDK objects. - AZ-NET-003: normalise direction, access, and source_address_prefix through enum_str() so real SecurityRuleDirection/SecurityRuleAccess enum values are detected correctly, not just plain-string mocks. - AZ-DB-002: normalise the auditing policy state through enum_str() so a real BlobAuditingPolicyState.ENABLED value is not mistaken for disabled (false positive) or vice versa. - AZ-DB-002: malformed ARM IDs are now logged explicitly instead of silently skipped. - AZ-NET-003: the matched plural source_address_prefixes entry is now included in finding metadata. - Add regression tests using real azure-mgmt-network / azure-mgmt-sql SDK model classes (SecurityRule, SecurityRuleDirection, SecurityRuleAccess, ServerBlobAuditingPolicy, BlobAuditingPolicyState) rather than only SimpleNamespace/string-backed mocks, per SHAURYAKSHARMA24's review. - Sync branch with upstream dev (v0.3.0) and apply current ruff format gate, per ritiksah141's review. * fix: remove duplicate _diagnostic_settings init line --------- Co-authored-by: safidnadaf * feat(scanner): add enterprise App Registration and Managed Identity rules (#197) * feat(scanner): add enterprise identity security pack * docs(compliance): use numbered TBD identity placeholders * fix: update parse_resource_id test to match current resource_group behavior * feat(release): attest artifacts and require signed tags (#207) * feat(frontend): add accessibility and i18n foundations (#206) * docs: prepare OpenSSF Silver readiness evidence * feat(frontend): add accessibility and i18n foundations --------- Signed-off-by: Tanvir Farhad * fix: resolve all open security alerts (8 Dependabot + 1 CodeQL) (#222) * fix: resolve all open security alerts (8 Dependabot + 1 CodeQL) Closes #221. Dependency vulnerabilities: - react-router-dom (root and frontend) replaced with react-router 8.3.0. react-router v8 dropped the react-router-dom re-export package, so this is an import migration, not just a version bump: all 9 files that imported from react-router-dom (BrowserRouter, Routes, Route, Navigate, useLocation, useNavigate, NavLink, Outlet) now import from react-router directly, matching v8's actual export surface (react-router/dom only ships RouterProvider/HydratedRouter, which nothing here uses). Fixes Dependabot alerts #12, #10, #8, #7, #6, #5. - postcss bumped to 8.5.18+ (resolved to 8.5.25). Fixes alert #9. - brace-expansion bumped to 5.0.9 via npm audit fix, clearing both the originally reported alert #4 (exponential-time expansion DoS) and a second advisory affecting versions up to and including 5.0.7 (out-of-memory DoS) that the requested 5.0.7 floor would not have cleared on its own. CodeQL alert #31 (py/clear-text-logging-sensitive-data): - scanner/rules/az_idn_006.py logged the raw endDateTime value from a service principal's password credential when it failed to parse. Drops the value from the log line entirely; app_id alone is sufficient to correlate the failure. Matches the fix already proposed in draft PR #220, which this supersedes. - Strengthened the existing regression test to also assert the malformed endDateTime value itself never reaches the logs (it previously only checked keyId), and verified the test fails against the pre-fix code before restoring the fix. Added node_modules/ to the root .gitignore - the root package.json exists only to give Dependabot a manifest to track react-router against, but running npm install there to regenerate its lockfile was leaving an untracked node_modules/ with nothing preventing it from being committed. Verified: npm audit clean (root and frontend, 0 vulnerabilities each), frontend build and lint pass, ruff check/format clean, full pytest suite passes (437 passed, 2 pre-existing failures unrelated to this change - local chromadb version mismatch, not present in CI). Signed-off-by: Tanvir Farhad * style: fix ruff format drift on markdown-embedded Python examples CI's ruff (unpinned) reformatted the embedded code fences in CONTRIBUTING.md, docs/adding-a-rule.md, and docs/architecture.md again since the last fix in b9d4538 - whitespace only, no content changes. Signed-off-by: Tanvir Farhad * fix: declare react-router 8.3.0's runtime requirements per review react-router@8.3.0 requires Node >=22.22.0 and react/react-dom >=19.2.7 (peer deps). Bump the declared React floors, add an engines.node field to frontend/package.json, and pin CI's frontend job to Node 22.22.0 so the requirement is enforced rather than relying on "latest 22.x" happening to be new enough. Addresses ritiksah141's CHANGES_REQUESTED review on PR #222. Signed-off-by: Tanvir Farhad --------- Signed-off-by: Tanvir Farhad * feat(scanner): add Supply Chain security pack (AZ-SC-001..008) (#219) * feat(scanner): add Supply Chain security pack (AZ-SC-001..008) Closes the gap identified in #213: OpenShield had zero rules covering OWASP Top 10:2025's A03 Software Supply Chain Failures category, the highest-incidence category (5.72%) and one enterprise CSPM vendors treat as core coverage. Container Registry hardening (#214): - AZ-SC-001: admin user enabled - AZ-SC-002: public network access enabled - AZ-SC-003: anonymous pull enabled - AZ-SC-004: missing retention/quarantine policy New dependency: azure-mgmt-containerregistry. Terraform/IaC state exposure (#214): - AZ-SC-005: state container publicly readable - AZ-SC-006: state storage account missing versioning/soft delete Reuses the existing azure-mgmt-storage dependency at the per-container level via new AzureClient.get_blob_containers() and get_blob_service_properties() accessors. Azure DevOps pipeline scanning (#215, #216, #217): - New scanner/devops_client.py, reusing the existing service principal credential scoped to Azure DevOps' well-known resource ID rather than a separate stored credential (e.g. a PAT). - AzureClient.devops_client is None when AZURE_DEVOPS_ORG_URL / AZURE_DEVOPS_PROJECT are not configured; the two rules below treat that as not applicable, not an indeterminate failure. - AZ-SC-007: service connection scoped to subscription and shared across every pipeline - AZ-SC-008: service connection uses a stored secret instead of workload identity federation New dependency: azure-devops. All 8 rules are added to all four compliance framework JSONs (CIS, NIST CSF, ISO 27001, SOC 2) with matching control IDs, per the pattern established after PR #198's review. Signed-off-by: Tanvir Farhad * style: fix ruff format on markdown-embedded Python code blocks CI's ruff (installed fresh, unpinned) is newer than the local dev environment's and now reformats Python code fences inside markdown files. Reformats the embedded examples in CONTRIBUTING.md, docs/adding-a-rule.md, and docs/architecture.md - whitespace only, no content changes. Signed-off-by: Tanvir Farhad * fix: correct three real logic bugs found in self-review AZ-SC-004: quarantine is a Premium-tier-only ACR feature, but the rule required it on every registry regardless of SKU. Every Basic/Standard registry (the common tier) would permanently fail this check even when correctly hardened for its tier. Now only requires quarantine on Premium registries; retention is still required on all tiers. AZ-SC-007: is_shared means shared with other projects per the Azure DevOps SDK docs, not shared across every pipeline in this project as the rule claimed. Renamed to drop the and Shared framing and flag subscription-scoped connections on their scope alone, which is itself a real, sufficient finding regardless of is_shared. AZ-SC-008: the federated-scheme allowlist only included WorkloadIdentityFederation, missing ManagedServiceIdentity, a second, equally secretless authentication scheme. Service connections using managed identity auth were being incorrectly flagged as using a stored secret. Adds regression tests proving each fix, and updates the two rules compliance framework JSON entries and docs/rules-reference.md to match. Signed-off-by: Tanvir Farhad --------- Signed-off-by: Tanvir Farhad * governance: enforce DCO and document continuity checks (#208) * governance: enforce DCO and document continuity checks Signed-off-by: Tanvir Farhad * fix: exclude merge commits from the DCO sign-off check commits_between() checked every commit in the PR range including merge commits, which carry Git's own default message and no Signed-off-by trailer since they aren't the author's own work. This would have hard-failed the DCO gate on legitimate `git merge origin/dev` commits (e.g. the two that landed in #161's review cycle) through no fault of the contributor's own commits — GitHub's own DCO app skips merge commits for the same reason. Add --no-merges to the rev-list call and document the exemption in docs/dco.md so contributors know only their own commits need signing. Signed-off-by: Tanvir Farhad --------- Signed-off-by: Tanvir Farhad * fix: upgrade cryptography for CVE-2026-69247 (#226) Signed-off-by: ritiksah141 --------- Signed-off-by: dependabot[bot] Signed-off-by: Vishnu Ajith <27vishnu07@gmail.com> Signed-off-by: Tanvir Farhad Signed-off-by: ritiksah141 Co-authored-by: Tanvir Farhad Co-authored-by: PARTH J ROHIT Co-authored-by: Ritik Sah Co-authored-by: Shaurya K Sharma Co-authored-by: Shaurya K Sharma Co-authored-by: Mahfuzur Rahman Emon Co-authored-by: Safid Nadaf <137755124+safidnadaf@users.noreply.github.com> Co-authored-by: Abdulbosit Abdurazzakov <2d9c6kh58x@privaterelay.appleid.com> Co-authored-by: Mahfuzur Rahman Emon Co-authored-by: Prayas Gautam <159550781+vogonPrayas@users.noreply.github.com> Co-authored-by: Claude Sonnet 4.6 Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> Co-authored-by: Muhammad Ibrahim <135441675+m-khan-97@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: safidnadaf --- .env.example | 4 + .github/PULL_REQUEST_TEMPLATE.md | 1 + .github/workflows/dco.yml | 24 ++ CHANGELOG.md | 1 + .../frameworks/cis_azure_benchmark.json | 40 +++ compliance/frameworks/iso27001.json | 40 +++ compliance/frameworks/nist_csf.json | 40 +++ compliance/frameworks/soc2.json | 40 +++ docs/access-continuity.md | 37 +++ docs/adding-a-rule.md | 7 + docs/architecture.md | 12 +- docs/azure-setup.md | 22 ++ docs/dco.md | 33 ++ docs/rules-reference.md | 12 +- playbooks/cli/fix_az_sc_001.sh | 21 ++ playbooks/cli/fix_az_sc_002.sh | 21 ++ playbooks/cli/fix_az_sc_003.sh | 21 ++ playbooks/cli/fix_az_sc_004.sh | 23 ++ playbooks/cli/fix_az_sc_005.sh | 21 ++ playbooks/cli/fix_az_sc_006.sh | 23 ++ playbooks/cli/fix_az_sc_007.sh | 25 ++ playbooks/cli/fix_az_sc_008.sh | 27 ++ requirements.txt | 4 +- scanner/azure_client.py | 90 ++++++ scanner/devops_client.py | 79 +++++ scanner/rules/az_sc_001.py | 70 +++++ scanner/rules/az_sc_002.py | 71 +++++ scanner/rules/az_sc_003.py | 71 +++++ scanner/rules/az_sc_004.py | 91 ++++++ scanner/rules/az_sc_005.py | 85 +++++ scanner/rules/az_sc_006.py | 91 ++++++ scanner/rules/az_sc_007.py | 75 +++++ scanner/rules/az_sc_008.py | 81 +++++ scripts/check_dco.py | 68 ++++ tests/helpers/mock_azure.py | 33 ++ tests/test_azure_client_management.py | 59 ++++ tests/test_dco_check.py | 36 +++ tests/test_devops_client.py | 54 ++++ tests/test_rules_supply_chain.py | 294 ++++++++++++++++++ 39 files changed, 1839 insertions(+), 8 deletions(-) create mode 100644 .github/workflows/dco.yml create mode 100644 docs/access-continuity.md create mode 100644 docs/dco.md create mode 100644 playbooks/cli/fix_az_sc_001.sh create mode 100644 playbooks/cli/fix_az_sc_002.sh create mode 100644 playbooks/cli/fix_az_sc_003.sh create mode 100644 playbooks/cli/fix_az_sc_004.sh create mode 100644 playbooks/cli/fix_az_sc_005.sh create mode 100644 playbooks/cli/fix_az_sc_006.sh create mode 100644 playbooks/cli/fix_az_sc_007.sh create mode 100644 playbooks/cli/fix_az_sc_008.sh create mode 100644 scanner/devops_client.py create mode 100644 scanner/rules/az_sc_001.py create mode 100644 scanner/rules/az_sc_002.py create mode 100644 scanner/rules/az_sc_003.py create mode 100644 scanner/rules/az_sc_004.py create mode 100644 scanner/rules/az_sc_005.py create mode 100644 scanner/rules/az_sc_006.py create mode 100644 scanner/rules/az_sc_007.py create mode 100644 scanner/rules/az_sc_008.py create mode 100644 scripts/check_dco.py create mode 100644 tests/test_dco_check.py create mode 100644 tests/test_devops_client.py create mode 100644 tests/test_rules_supply_chain.py diff --git a/.env.example b/.env.example index e03fe417..ec0462b5 100644 --- a/.env.example +++ b/.env.example @@ -12,3 +12,7 @@ GEMINI_API_KEY= # Optional NVD_API_KEY= SENTRY_DSN= + +# Optional - enables AZ-SC-007/008 (Azure DevOps pipeline scanning) +AZURE_DEVOPS_ORG_URL= +AZURE_DEVOPS_PROJECT= diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index f5b031c0..2da9e0de 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -26,6 +26,7 @@ Closes # ## Checklist +- [ ] Every commit includes a DCO `Signed-off-by` trailer (`git commit -s`; see `docs/dco.md`) - [ ] My code follows the rule template in CONTRIBUTING.md - [ ] I added or updated the matching CLI playbook - [ ] I added or updated all four compliance framework mappings diff --git a/.github/workflows/dco.yml b/.github/workflows/dco.yml new file mode 100644 index 00000000..ac25e314 --- /dev/null +++ b/.github/workflows/dco.yml @@ -0,0 +1,24 @@ +name: Developer Certificate of Origin + +on: + pull_request: + branches: [dev, main] + +permissions: + contents: read + +jobs: + signoff: + name: DCO sign-off + runs-on: ubuntu-latest + steps: + - name: Checkout pull request history + uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + with: + fetch-depth: 0 + + - name: Verify every pull request commit + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: python scripts/check_dco.py "$BASE_SHA" "$HEAD_SHA" diff --git a/CHANGELOG.md b/CHANGELOG.md index 408c9daa..9f85576b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,7 @@ OpenShield uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ### Security +- Upgraded cryptography to 50.0.0 to address CVE-2026-69247 - AI provider errors no longer expose upstream response details - Request body limits, AI rate limiting, and playbook path validation added - GitHub Actions dependencies pinned to immutable commit SHAs diff --git a/compliance/frameworks/cis_azure_benchmark.json b/compliance/frameworks/cis_azure_benchmark.json index 78112c3b..25146ecd 100644 --- a/compliance/frameworks/cis_azure_benchmark.json +++ b/compliance/frameworks/cis_azure_benchmark.json @@ -287,6 +287,46 @@ "control_id": "TBD-IDN-015", "control_name": "Managed Identity least privilege (not mapped in CIS Azure Foundations 2.0.0)", "description": "Microsoft recommends least-privilege roles and scopes for managed identities. This check has no direct control in the repository's CIS Azure Foundations 2.0.0 benchmark." + }, + "AZ-SC-001": { + "control_id": "TBD-SC-001", + "control_name": "Container Registry Admin User Enabled placeholder", + "description": "Numbered placeholder pending maintainer approval of a direct CIS mapping." + }, + "AZ-SC-002": { + "control_id": "TBD-SC-002", + "control_name": "Container Registry Public Network Access Enabled placeholder", + "description": "Numbered placeholder pending maintainer approval of a direct CIS mapping." + }, + "AZ-SC-003": { + "control_id": "TBD-SC-003", + "control_name": "Container Registry Allows Anonymous Pull placeholder", + "description": "Numbered placeholder pending maintainer approval of a direct CIS mapping." + }, + "AZ-SC-004": { + "control_id": "TBD-SC-004", + "control_name": "Container Registry Missing Retention or Quarantine Policy placeholder", + "description": "Numbered placeholder pending maintainer approval of a direct CIS mapping." + }, + "AZ-SC-005": { + "control_id": "TBD-SC-005", + "control_name": "Terraform State Storage Container Publicly Readable placeholder", + "description": "Numbered placeholder pending maintainer approval of a direct CIS mapping." + }, + "AZ-SC-006": { + "control_id": "TBD-SC-006", + "control_name": "Terraform State Storage Account Missing Versioning or Soft Delete placeholder", + "description": "Numbered placeholder pending maintainer approval of a direct CIS mapping." + }, + "AZ-SC-007": { + "control_id": "TBD-SC-007", + "control_name": "Pipeline Service Connection Scoped to Subscription placeholder", + "description": "Numbered placeholder pending maintainer approval of a direct CIS mapping." + }, + "AZ-SC-008": { + "control_id": "TBD-SC-008", + "control_name": "Pipeline Service Connection Uses Password Instead of Federated Credential placeholder", + "description": "Numbered placeholder pending maintainer approval of a direct CIS mapping." } } } diff --git a/compliance/frameworks/iso27001.json b/compliance/frameworks/iso27001.json index c4b88d8e..0ab3c86f 100644 --- a/compliance/frameworks/iso27001.json +++ b/compliance/frameworks/iso27001.json @@ -287,6 +287,46 @@ "control_id": "A.9.2.3", "control_name": "Management of privileged access rights", "description": "Subscription Owner and Contributor assignments to managed identities require least-privilege reduction." + }, + "AZ-SC-001": { + "control_id": "A.9.2.1", + "control_name": "User registration and de-registration", + "description": "The Container Registry admin user is enabled, providing a shared credential that bypasses individual identity management and cannot be attributed to a single user." + }, + "AZ-SC-002": { + "control_id": "A.13.1.1", + "control_name": "Network controls", + "description": "The Container Registry is reachable from the public internet, leaving the network boundary that protects the organization's built container images uncontrolled." + }, + "AZ-SC-003": { + "control_id": "A.9.2.1", + "control_name": "User registration and de-registration", + "description": "The Container Registry allows anonymous pull, letting any client access every image without an authenticated, individually attributable identity." + }, + "AZ-SC-004": { + "control_id": "A.12.1.2", + "control_name": "Change management", + "description": "The Container Registry has no retention or quarantine policy, so stale images accumulate and newly pushed images are deployable before any vulnerability scan evaluates them." + }, + "AZ-SC-005": { + "control_id": "A.13.1.1", + "control_name": "Network controls", + "description": "A Terraform remote state container is publicly readable, leaving the network boundary around infrastructure layout and captured secrets uncontrolled." + }, + "AZ-SC-006": { + "control_id": "A.12.3.1", + "control_name": "Information backup", + "description": "A storage account holding Terraform remote state has neither versioning nor soft delete enabled, so an overwritten or deleted state file cannot be recovered." + }, + "AZ-SC-007": { + "control_id": "A.9.2.3", + "control_name": "Management of privileged access rights", + "description": "A pipeline service connection is scoped to the entire subscription rather than a single resource group, so every pipeline that uses it inherits subscription-wide access beyond what it needs." + }, + "AZ-SC-008": { + "control_id": "A.9.4.3", + "control_name": "Password management system", + "description": "A pipeline service connection authenticates with a stored service principal secret instead of a federated credential, leaving a static credential to rotate and potentially leak." } } } diff --git a/compliance/frameworks/nist_csf.json b/compliance/frameworks/nist_csf.json index 563c614f..69167b37 100644 --- a/compliance/frameworks/nist_csf.json +++ b/compliance/frameworks/nist_csf.json @@ -287,6 +287,46 @@ "control_id": "PR.AC-4", "control_name": "Access permissions and authorizations are managed", "description": "Managed identities should receive only the minimum role and scope required by their workloads." + }, + "AZ-SC-001": { + "control_id": "PR.AC-1", + "control_name": "Identities and credentials are issued, managed, verified, revoked, and audited", + "description": "The Container Registry admin user is enabled, providing a shared credential that bypasses individual identity management and cannot be attributed to a single user." + }, + "AZ-SC-002": { + "control_id": "PR.AC-5", + "control_name": "Network integrity is protected", + "description": "The Container Registry is reachable from the public internet, leaving the network boundary that protects the organization's built container images uncontrolled." + }, + "AZ-SC-003": { + "control_id": "PR.AC-1", + "control_name": "Identities and credentials are issued, managed, verified, revoked, and audited", + "description": "The Container Registry allows anonymous pull, letting any client access every image without an authenticated, individually attributable identity." + }, + "AZ-SC-004": { + "control_id": "PR.IP-1", + "control_name": "A baseline configuration is created and maintained", + "description": "The Container Registry has no retention or quarantine policy, so stale images accumulate and newly pushed images are deployable before any vulnerability scan evaluates them." + }, + "AZ-SC-005": { + "control_id": "PR.AC-5", + "control_name": "Network integrity is protected", + "description": "A Terraform remote state container is publicly readable, leaving the network boundary around infrastructure layout and captured secrets uncontrolled." + }, + "AZ-SC-006": { + "control_id": "PR.IP-4", + "control_name": "Backups of information are conducted, maintained, and tested", + "description": "A storage account holding Terraform remote state has neither versioning nor soft delete enabled, so an overwritten or deleted state file cannot be recovered." + }, + "AZ-SC-007": { + "control_id": "PR.AC-4", + "control_name": "Access permissions and authorizations are managed", + "description": "A pipeline service connection is scoped to the entire subscription rather than a single resource group, so every pipeline that uses it inherits subscription-wide access beyond what it needs." + }, + "AZ-SC-008": { + "control_id": "PR.AC-1", + "control_name": "Identities and credentials are issued, managed, verified, revoked, and audited", + "description": "A pipeline service connection authenticates with a stored service principal secret instead of a federated credential, leaving a static credential to rotate and potentially leak." } } } diff --git a/compliance/frameworks/soc2.json b/compliance/frameworks/soc2.json index 56457932..ba19486c 100644 --- a/compliance/frameworks/soc2.json +++ b/compliance/frameworks/soc2.json @@ -287,6 +287,46 @@ "control_id": "CC6.3", "control_name": "Role-Based Access", "description": "Managed identities should not receive broad subscription roles beyond workload requirements." + }, + "AZ-SC-001": { + "control_id": "CC6.1", + "control_name": "Logical Access Security Measures", + "description": "The Container Registry admin user is enabled, providing a shared credential that bypasses individual identity management and cannot be attributed to a single user." + }, + "AZ-SC-002": { + "control_id": "CC6.6", + "control_name": "Restricts Access from Outside the Network Boundary", + "description": "The Container Registry is reachable from the public internet, leaving the network boundary that protects the organization's built container images uncontrolled." + }, + "AZ-SC-003": { + "control_id": "CC6.1", + "control_name": "Logical Access Security Measures", + "description": "The Container Registry allows anonymous pull, letting any client access every image without an authenticated, individually attributable identity." + }, + "AZ-SC-004": { + "control_id": "CC7.1", + "control_name": "System Vulnerabilities are Identified and Managed", + "description": "The Container Registry has no retention or quarantine policy, so stale images accumulate and newly pushed images are deployable before any vulnerability scan evaluates them." + }, + "AZ-SC-005": { + "control_id": "CC6.6", + "control_name": "Restricts Access from Outside the Network Boundary", + "description": "A Terraform remote state container is publicly readable, leaving the network boundary around infrastructure layout and captured secrets uncontrolled." + }, + "AZ-SC-006": { + "control_id": "A1.2", + "control_name": "Environmental Threats and Recovery", + "description": "A storage account holding Terraform remote state has neither versioning nor soft delete enabled, so an overwritten or deleted state file cannot be recovered." + }, + "AZ-SC-007": { + "control_id": "CC6.1", + "control_name": "Logical Access Security Measures", + "description": "A pipeline service connection is scoped to the entire subscription rather than a single resource group, so every pipeline that uses it inherits subscription-wide access beyond what it needs." + }, + "AZ-SC-008": { + "control_id": "CC6.1", + "control_name": "Logical Access Security Measures", + "description": "A pipeline service connection authenticates with a stored service principal secret instead of a federated credential, leaving a static credential to rotate and potentially leak." } } } diff --git a/docs/access-continuity.md b/docs/access-continuity.md new file mode 100644 index 00000000..f366598c --- /dev/null +++ b/docs/access-continuity.md @@ -0,0 +1,37 @@ +# Project Access Continuity + +OpenShield's public component ownership is recorded in `.github/CODEOWNERS`. +OpenSSF continuity requires more than public names: organization owners must +verify that the project can continue if any one person becomes unavailable. + +## Required capability matrix + +At least two currently available people must independently be able to perform +each critical capability, or use a tested organization-controlled recovery +process: + +| Capability | Primary confirmed | Backup confirmed | Last tested | +|---|---|---|---| +| Triage and close issues | Owner record | Owner record | Date required | +| Review and merge approved changes | Owner record | Owner record | Date required | +| Publish and verify a release | Owner record | Owner record | Date required | +| Recover GitHub organization access | Owner record | Owner record | Date required | +| Manage production deployment access | Owner record | Owner record | Date required | +| Manage domain/DNS access, if applicable | Owner record | Owner record | Date required | +| Rotate security-reporting access | Owner record | Owner record | Date required | + +Names and recovery details may remain in a private owner-controlled record when +publishing them would increase risk. The public OpenSSF justification should +state the date of verification and that two independent holders were confirmed, +without exposing secrets. + +## Review process + +- Review the matrix at least every six months and before each major release. +- Remove access promptly when a role ends and confirm the backup remains valid. +- Test recovery without sharing credentials between individuals. +- Store recovery material outside any single maintainer's personal account. +- Record the review in issue #205 or another auditable owner-approved record. + +The continuity and bus-factor criteria must remain pending until an organization +owner completes and records this verification. Documentation alone is not proof. diff --git a/docs/adding-a-rule.md b/docs/adding-a-rule.md index ee12e814..65fd5e14 100644 --- a/docs/adding-a-rule.md +++ b/docs/adding-a-rule.md @@ -131,12 +131,19 @@ def scan(azure_client: Any, subscription_id: str) -> List[Dict[str, Any]]: | `azure_client.get_subscription_role_assignments()` | Subscription RBAC assignments, or `None` on API failure | | `azure_client.get_service_principals()` | List of RoleAssignment objects for service principals | | `azure_client.get_conditional_access_policies()` | List of CA policy dicts from MS Graph | +| `azure_client.get_container_registries()` | List of ACR Registry objects, or `None` on API failure | +| `azure_client.get_blob_containers(rg, account)` | List of blob container items (with `public_access`), or `None` on API failure | +| `azure_client.get_blob_service_properties(rg, account)` | BlobServiceProperties (versioning, soft delete), or `None` on API failure | +| `azure_client.devops_client` | `DevOpsClient` instance, or `None` if `AZURE_DEVOPS_ORG_URL`/`AZURE_DEVOPS_PROJECT` are not configured | +| `azure_client.devops_client.get_service_endpoints()` | List of Azure DevOps service connections, or `None` on API failure | | `azure_client.parse_resource_id(id)` | Dict with `resource_group` and `name` | List methods return an empty list on failure. Single-resource methods return `None` when the resource cannot be fetched. Three-state checks, such as `get_storage_lifecycle_policy()`, return `True` for compliant, `False` for non-compliant, and `None` when the scanner cannot determine the state. When a helper returns `None`, skip the resource and log a warning. Never create a finding from an unknown state. +`azure_client.devops_client` is `None` whenever Azure DevOps is not configured for the scanned subscription — treat that the same as "not applicable" and return no findings, not as an indeterminate failure. + --- ## Write the Remediation Playbook diff --git a/docs/architecture.md b/docs/architecture.md index 317bc7e5..f8fa9f50 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -2,7 +2,7 @@ ## Overview -OpenShield is a modular, open source Cloud Security Posture Management (CSPM) platform for Azure. It scans your Azure subscription against 51 security rules, maps findings to compliance frameworks (CIS, NIST CSF, ISO 27001, SOC 2), stores results in PostgreSQL, and exposes posture data through a Flask REST API consumed by a live React dashboard. +OpenShield is a modular, open source Cloud Security Posture Management (CSPM) platform for Azure. It scans your Azure subscription against 65 security rules, maps findings to compliance frameworks (CIS, NIST CSF, ISO 27001, SOC 2), stores results in PostgreSQL, and exposes posture data through a Flask REST API consumed by a live React dashboard. --- @@ -43,8 +43,9 @@ OpenShield is a modular, open source Cloud Security Posture Management (CSPM) pl ┌───────────▼──────────────────────────────────────────────────────┐ │ Rule Modules (scanner/rules/) │ │ │ -│ 51 rule files across Storage, Network, Identity, Database, │ -│ Compute, Key Vault, AKS, and post-quantum cryptography │ +│ 65 rule files across Storage, Network, Identity, Database, │ +│ Compute, Key Vault, AKS, post-quantum cryptography, and │ +│ Supply Chain (Container Registry, IaC state, DevOps pipelines) │ └───────────┬───────────────────────────────────────────────────────┘ │ calls ┌───────────▼──────────────────────────────────────────────────────┐ @@ -110,18 +111,19 @@ result = engine.run_scan() ### 4. Current Rule Modules -There are 51 rule files in `scanner/rules/`. See `docs/rules-reference.md` for the full table. +There are 65 rule files in `scanner/rules/`. See `docs/rules-reference.md` for the full table. | Category | Count | Rules | |---|---|---| | Storage | 5 | AZ-STOR-001 to 005 | | Network | 15 | AZ-NET-001 to 015 | -| Identity | 4 | AZ-IDN-001 to 004 | +| Identity | 15 | AZ-IDN-001 to 015 | | Database | 4 | AZ-DB-001 to 004 | | Compute | 4 | AZ-CMP-001 to 004 | | Key Vault | 5 | AZ-KV-001 to 005 | | Kubernetes | 6 | AZ-AKS-001 to 006 | | Post-quantum | 3 | AZ-PQC-001 to 003 | +| Supply Chain | 8 | AZ-SC-001 to 008 | Every rule has a matching Azure CLI playbook in `playbooks/cli/`. diff --git a/docs/azure-setup.md b/docs/azure-setup.md index 63e345ea..36d21f93 100644 --- a/docs/azure-setup.md +++ b/docs/azure-setup.md @@ -282,6 +282,27 @@ The AZ-DB-002 remediation playbook writes SQL audit logs to a storage account. T --- +## Step 10 — Configure Azure DevOps Pipeline Scanning (Optional) + +AZ-SC-007 and AZ-SC-008 check Azure DevOps pipeline service connections for +subscription-wide sharing and password-based authentication. Azure DevOps is +a separate system from Azure Resource Manager, so it needs two additional +environment variables. Both must be set or neither rule will produce +findings — this is treated as "not applicable," not an error. + +```bash +AZURE_DEVOPS_ORG_URL=https://dev.azure.com/your-org +AZURE_DEVOPS_PROJECT=your-project-name +``` + +The scanner reuses the same service principal configured in Step 3, requesting +a token scoped to Azure DevOps' well-known resource ID +(`499b84ac-1321-427f-aa17-267ca6975798`). Grant that service principal at +least **Reader** access to the target Azure DevOps project's service +connections (Project Settings > Service connections > Security). + +--- + ## Troubleshooting | Problem | Fix | @@ -291,3 +312,4 @@ The AZ-DB-002 remediation playbook writes SQL audit logs to a storage account. T | `psycopg2.OperationalError` | Check your PostgreSQL container is running and `DATABASE_URL` is correct | | Empty findings | Verify the service principal has `Reader` role on the subscription | | AZ-IDN-002 always fires | The service principal needs `Policy.Read.All` Graph permission — see Step 4 | +| AZ-SC-007/008 never fire | Confirm `AZURE_DEVOPS_ORG_URL` and `AZURE_DEVOPS_PROJECT` are both set — see Step 10 | diff --git a/docs/dco.md b/docs/dco.md new file mode 100644 index 00000000..98762442 --- /dev/null +++ b/docs/dco.md @@ -0,0 +1,33 @@ +# Developer Certificate of Origin + +OpenShield uses the [Developer Certificate of Origin 1.1](https://developercertificate.org/) +as its contribution authorization mechanism. A `Signed-off-by` trailer states +that the contributor is legally entitled to submit the work under the project's +license and agrees to the DCO certification. + +Add the trailer automatically when committing: + +```bash +git commit -s -m "feat: describe the change" +``` + +The name and email in the trailer should identify the contributor and should +match the commit author unless a documented contribution workflow requires a +different authorized signer. Every non-merge commit introduced by a pull +request is checked; a sign-off only in the pull request description is +insufficient. + +Merge commits (e.g. from running `git merge origin/dev` to bring your branch +up to date) are exempt — they carry Git's own default message, not your +authorship, so there is nothing for you to sign off on. Only commits you +authored yourself need the trailer. + +To repair the latest local commit before review: + +```bash +git commit --amend --signoff --no-edit +git push --force-with-lease +``` + +For multiple commits, use an interactive rebase and add a sign-off to each +commit. Do not add another person's sign-off without their authorization. diff --git a/docs/rules-reference.md b/docs/rules-reference.md index 8b2b4f5d..22288cf2 100644 --- a/docs/rules-reference.md +++ b/docs/rules-reference.md @@ -1,6 +1,6 @@ -# Rules Reference +# Rules Reference -OpenShield currently ships 51 Azure scan rules. This table is generated from the module-level constants in `scanner/rules/`. +OpenShield currently ships 65 Azure scan rules. This table is generated from the module-level constants in `scanner/rules/`. | Rule ID | Name | Severity | Category | CIS | NIST | ISO 27001 | |---|---|---|---|---|---|---| @@ -61,6 +61,14 @@ OpenShield currently ships 51 Azure scan rules. This table is generated from the | AZ-AKS-004 | AKS Workload Identity Not Fully Enabled | MEDIUM | Kubernetes | N/A-AKS-004 | PR.AC-4 | A.9.2.3 | | AZ-AKS-005 | AKS Azure Policy Add-on Not Enabled | MEDIUM | Kubernetes | N/A-AKS-005 | PR.IP-1 | A.12.1.2 | | AZ-AKS-006 | AKS Node OS Automatic Upgrades Disabled | HIGH | Kubernetes | N/A-AKS-006 | PR.IP-12 | A.12.6.1 | +| AZ-SC-001 | Container Registry Admin User Enabled | HIGH | Supply Chain | TBD-SC-001 | PR.AC-1 | A.9.2.1 | +| AZ-SC-002 | Container Registry Public Network Access Enabled | HIGH | Supply Chain | TBD-SC-002 | PR.AC-5 | A.13.1.1 | +| AZ-SC-003 | Container Registry Allows Anonymous Pull | HIGH | Supply Chain | TBD-SC-003 | PR.AC-1 | A.9.2.1 | +| AZ-SC-004 | Container Registry Missing Retention or Quarantine Policy | MEDIUM | Supply Chain | TBD-SC-004 | PR.IP-1 | A.12.1.2 | +| AZ-SC-005 | Terraform State Storage Container Publicly Readable | CRITICAL | Supply Chain | TBD-SC-005 | PR.AC-5 | A.13.1.1 | +| AZ-SC-006 | Terraform State Storage Account Missing Versioning or Soft Delete | HIGH | Supply Chain | TBD-SC-006 | PR.IP-4 | A.12.3.1 | +| AZ-SC-007 | Pipeline Service Connection Scoped to Subscription | HIGH | Supply Chain | TBD-SC-007 | PR.AC-4 | A.9.2.3 | +| AZ-SC-008 | Pipeline Service Connection Uses Password Instead of Federated Credential | MEDIUM | Supply Chain | TBD-SC-008 | PR.AC-1 | A.9.4.3 | SOC 2 mappings are maintained in `compliance/frameworks/soc2.json`. diff --git a/playbooks/cli/fix_az_sc_001.sh b/playbooks/cli/fix_az_sc_001.sh new file mode 100644 index 00000000..52277b1b --- /dev/null +++ b/playbooks/cli/fix_az_sc_001.sh @@ -0,0 +1,21 @@ +#!/bin/bash + +set -euo pipefail + +REGISTRY_NAME="${1:-}" +RESOURCE_GROUP="${2:-}" + +if [[ -z "$REGISTRY_NAME" || -z "$RESOURCE_GROUP" ]]; then + echo "Usage: $0 " + exit 1 +fi + +echo "Disabling admin user for Container Registry: $REGISTRY_NAME (RG: $RESOURCE_GROUP)" + +az acr update \ + --name "$REGISTRY_NAME" \ + --resource-group "$RESOURCE_GROUP" \ + --admin-enabled false + +echo "Admin user disabled successfully." +echo "Next step: Authenticate with Azure AD identities or a managed identity instead." diff --git a/playbooks/cli/fix_az_sc_002.sh b/playbooks/cli/fix_az_sc_002.sh new file mode 100644 index 00000000..884cf730 --- /dev/null +++ b/playbooks/cli/fix_az_sc_002.sh @@ -0,0 +1,21 @@ +#!/bin/bash + +set -euo pipefail + +REGISTRY_NAME="${1:-}" +RESOURCE_GROUP="${2:-}" + +if [[ -z "$REGISTRY_NAME" || -z "$RESOURCE_GROUP" ]]; then + echo "Usage: $0 " + exit 1 +fi + +echo "Disabling public network access for Container Registry: $REGISTRY_NAME (RG: $RESOURCE_GROUP)" + +az acr update \ + --name "$REGISTRY_NAME" \ + --resource-group "$RESOURCE_GROUP" \ + --public-network-enabled false + +echo "Public network access disabled successfully." +echo "Next step: Configure a private endpoint if the registry needs to be reachable from a VNet." diff --git a/playbooks/cli/fix_az_sc_003.sh b/playbooks/cli/fix_az_sc_003.sh new file mode 100644 index 00000000..800ab64d --- /dev/null +++ b/playbooks/cli/fix_az_sc_003.sh @@ -0,0 +1,21 @@ +#!/bin/bash + +set -euo pipefail + +REGISTRY_NAME="${1:-}" +RESOURCE_GROUP="${2:-}" + +if [[ -z "$REGISTRY_NAME" || -z "$RESOURCE_GROUP" ]]; then + echo "Usage: $0 " + exit 1 +fi + +echo "Disabling anonymous pull for Container Registry: $REGISTRY_NAME (RG: $RESOURCE_GROUP)" +echo "If this registry is intentionally used for public OCI distribution, do not run this script." + +az acr update \ + --name "$REGISTRY_NAME" \ + --resource-group "$RESOURCE_GROUP" \ + --anonymous-pull-enabled false + +echo "Anonymous pull disabled successfully." diff --git a/playbooks/cli/fix_az_sc_004.sh b/playbooks/cli/fix_az_sc_004.sh new file mode 100644 index 00000000..c2707108 --- /dev/null +++ b/playbooks/cli/fix_az_sc_004.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +set -euo pipefail + +REGISTRY_NAME="${1:-}" +RESOURCE_GROUP="${2:-}" +RETENTION_DAYS="${3:-30}" + +if [[ -z "$REGISTRY_NAME" || -z "$RESOURCE_GROUP" ]]; then + echo "Usage: $0 [retention-days]" + exit 1 +fi + +echo "Enabling untagged-manifest retention for Container Registry: $REGISTRY_NAME (RG: $RESOURCE_GROUP)" + +az acr config retention update \ + --registry "$REGISTRY_NAME" \ + --status enabled \ + --days "$RETENTION_DAYS" + +echo "Retention policy enabled ($RETENTION_DAYS days)." +echo "Quarantine policy has no dedicated Azure CLI command and requires the Premium SKU." +echo "Enable it via ARM/Bicep by setting properties.policies.quarantinePolicy.status to 'enabled'." diff --git a/playbooks/cli/fix_az_sc_005.sh b/playbooks/cli/fix_az_sc_005.sh new file mode 100644 index 00000000..63417ffb --- /dev/null +++ b/playbooks/cli/fix_az_sc_005.sh @@ -0,0 +1,21 @@ +#!/bin/bash + +set -euo pipefail + +ACCOUNT_NAME="${1:-}" +CONTAINER_NAME="${2:-}" + +if [[ -z "$ACCOUNT_NAME" || -z "$CONTAINER_NAME" ]]; then + echo "Usage: $0 " + exit 1 +fi + +echo "Setting public access to Off for container: $CONTAINER_NAME (account: $ACCOUNT_NAME)" + +az storage container set-permission \ + --name "$CONTAINER_NAME" \ + --account-name "$ACCOUNT_NAME" \ + --public-access off + +echo "Public access disabled successfully." +echo "Next step: confirm no anonymous access policy or SAS token grants broader access than intended." diff --git a/playbooks/cli/fix_az_sc_006.sh b/playbooks/cli/fix_az_sc_006.sh new file mode 100644 index 00000000..9349c734 --- /dev/null +++ b/playbooks/cli/fix_az_sc_006.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +set -euo pipefail + +ACCOUNT_NAME="${1:-}" +RESOURCE_GROUP="${2:-}" +RETENTION_DAYS="${3:-30}" + +if [[ -z "$ACCOUNT_NAME" || -z "$RESOURCE_GROUP" ]]; then + echo "Usage: $0 [retention-days]" + exit 1 +fi + +echo "Enabling blob versioning and soft delete for storage account: $ACCOUNT_NAME (RG: $RESOURCE_GROUP)" + +az storage account blob-service-properties update \ + --account-name "$ACCOUNT_NAME" \ + --resource-group "$RESOURCE_GROUP" \ + --enable-versioning true \ + --enable-delete-retention true \ + --delete-retention-days "$RETENTION_DAYS" + +echo "Blob versioning and soft delete ($RETENTION_DAYS-day retention) enabled successfully." diff --git a/playbooks/cli/fix_az_sc_007.sh b/playbooks/cli/fix_az_sc_007.sh new file mode 100644 index 00000000..0e948e6a --- /dev/null +++ b/playbooks/cli/fix_az_sc_007.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +set -euo pipefail + +echo "Azure DevOps service connections cannot have their scope changed in place; the" +echo "Azure CLI and REST API only support deleting and re-creating them." +echo +echo "1. Identify which pipelines actually need this service connection:" +echo " az pipelines list --project " +echo +echo "2. Create a new service connection scoped to only the resource group each" +echo " pipeline needs, instead of the whole subscription:" +echo " az devops service-endpoint azurerm create \\" +echo " --azure-rm-service-principal-id \\" +echo " --azure-rm-subscription-id \\" +echo " --azure-rm-subscription-name \\" +echo " --azure-rm-tenant-id \\" +echo " --name \\" +echo " --project " +echo +echo "3. Update each pipeline's YAML or classic definition to reference the new," +echo " narrowly scoped connection instead of the shared subscription-wide one." +echo +echo "4. Once no pipeline references the old connection, delete it:" +echo " az devops service-endpoint delete --id --project --yes" diff --git a/playbooks/cli/fix_az_sc_008.sh b/playbooks/cli/fix_az_sc_008.sh new file mode 100644 index 00000000..2c98323d --- /dev/null +++ b/playbooks/cli/fix_az_sc_008.sh @@ -0,0 +1,27 @@ +#!/bin/bash + +set -euo pipefail + +echo "Azure DevOps service connections cannot have their authentication scheme" +echo "changed in place; a password-based connection must be re-created as federated." +echo +echo "1. Create a new service connection using workload identity federation:" +echo " az devops service-endpoint azurerm create \\" +echo " --azure-rm-service-principal-id \\" +echo " --azure-rm-subscription-id \\" +echo " --azure-rm-subscription-name \\" +echo " --azure-rm-tenant-id \\" +echo " --service-principal-type federated \\" +echo " --name \\" +echo " --project " +echo +echo " (Federated auth is also available directly in the Azure DevOps UI:" +echo " Project Settings > Service connections > New service connection >" +echo " Azure Resource Manager > Workload identity federation.)" +echo +echo "2. Update each pipeline's YAML or classic definition to reference the new," +echo " federated connection instead of the password-based one." +echo +echo "3. Once no pipeline references the old connection, delete it and revoke the" +echo " underlying service principal secret it depended on:" +echo " az devops service-endpoint delete --id --project --yes" diff --git a/requirements.txt b/requirements.txt index 321fcb1b..bb2abccc 100644 --- a/requirements.txt +++ b/requirements.txt @@ -21,11 +21,13 @@ pyjwt==2.13.0 requests==2.34.2 PyYAML==6.0.3 gunicorn==26.0.0 -cryptography==49.0.0 +cryptography==50.0.0 msrest==0.7.1 azure-mgmt-postgresqlflexibleservers==1.0.0b1 azure-keyvault-certificates==4.8.0 azure-keyvault-keys==4.9.0 +azure-mgmt-containerregistry==15.0.0 +azure-devops==7.1.0b4 chromadb==0.4.24 numpy<2.0 prometheus-client>=0.19.0 diff --git a/scanner/azure_client.py b/scanner/azure_client.py index f0e4abbf..7e85d525 100644 --- a/scanner/azure_client.py +++ b/scanner/azure_client.py @@ -54,6 +54,25 @@ def __init__(self, subscription_id: str, credential: Optional[Any] = None) -> No self._applications_cache: Any = _UNSET self._managed_identity_principals_cache: Any = _UNSET self._subscription_role_assignments_cache: Any = _UNSET + self._container_registries_cache: Any = _UNSET + self.devops_client = self._build_devops_client() + + def _build_devops_client(self) -> Optional[Any]: + """Return a DevOpsClient if AZURE_DEVOPS_ORG_URL and AZURE_DEVOPS_PROJECT + are configured, else None. Absence is a deliberate opt-out (not every + subscription has an associated Azure DevOps organization), so rules + that depend on this must treat None as "not configured, skip" rather + than "unknown, indeterminate".""" + import os + + org_url = os.environ.get("AZURE_DEVOPS_ORG_URL") + project = os.environ.get("AZURE_DEVOPS_PROJECT") + if not org_url or not project: + return None + + from scanner.devops_client import DevOpsClient + + return DevOpsClient(org_url, project, credential=self.credential) # ------------------------------------------------------------------ # # Static helpers # @@ -662,3 +681,74 @@ def get_network_watcher_regions(self) -> List[str]: except Exception as exc: logger.error("get_network_watcher_regions failed: %s", exc) return [] + + # ------------------------------------------------------------------ # + # Supply chain: Container Registry, IaC state # + # ------------------------------------------------------------------ # + + def get_container_registries(self) -> Optional[List[Any]]: + """List Azure Container Registries, preserving an indeterminate failure state. + + Cached for the lifetime of this client because all AZ-SC container + registry rules evaluate the same subscription-level collection. + + Returns: + A list (including an empty list) when Azure responds successfully, + or ``None`` when permissions, networking, or the SDK prevent the + collection from being evaluated. Callers must never interpret + ``None`` as a compliant result. + """ + if self._container_registries_cache is not _UNSET: + return self._container_registries_cache + + try: + from azure.mgmt.containerregistry import ContainerRegistryManagementClient + + client = ContainerRegistryManagementClient(self.credential, self.subscription_id) + self._container_registries_cache = list(client.registries.list()) + except Exception as exc: + logger.error("get_container_registries failed: %s", exc) + self._container_registries_cache = None + return self._container_registries_cache + + def get_blob_containers(self, resource_group: str, account_name: str) -> Optional[List[Any]]: + """List blob containers for a storage account, including per-container access level. + + Not cached: unlike the subscription-wide collections above, this is + called once per storage account rather than once per scan. + + Returns: + A list of container items, or ``None`` when the call fails + (permissions, throttling, storage account not found). + """ + try: + client = StorageManagementClient(self.credential, self.subscription_id) + return list(client.blob_containers.list(resource_group, account_name)) + except Exception as exc: + logger.error( + "get_blob_containers(%s/%s) failed: %s", + resource_group, + account_name, + exc, + ) + return None + + def get_blob_service_properties(self, resource_group: str, account_name: str) -> Optional[Any]: + """Return account-wide blob service properties (versioning, soft-delete retention). + + Not cached, for the same reason as get_blob_containers above. + + Returns: + A BlobServiceProperties object, or ``None`` when the call fails. + """ + try: + client = StorageManagementClient(self.credential, self.subscription_id) + return client.blob_services.get_service_properties(resource_group, account_name) + except Exception as exc: + logger.error( + "get_blob_service_properties(%s/%s) failed: %s", + resource_group, + account_name, + exc, + ) + return None diff --git a/scanner/devops_client.py b/scanner/devops_client.py new file mode 100644 index 00000000..382a5def --- /dev/null +++ b/scanner/devops_client.py @@ -0,0 +1,79 @@ +"""Azure DevOps API wrapper for Supply Chain pipeline/service-connection rules. + +Separate from AzureClient because Azure DevOps lives at dev.azure.com, not +Azure Resource Manager, and needs its own configuration (organization URL, +project name) that an ARM subscription ID does not carry. Reuses the same +DefaultAzureCredential already used for the Azure subscription, scoped to +Azure DevOps' well-known Entra ID resource ID, so no separate stored +credential (e.g. a PAT) is required. +""" + +import logging +from typing import Any, List, Optional + +logger = logging.getLogger(__name__) + +# Well-known Entra ID resource ID for Azure DevOps. Used as the OAuth scope +# when requesting a token from the same credential AzureClient already uses. +AZURE_DEVOPS_RESOURCE_ID = "499b84ac-1321-427f-aa17-267ca6975798" + +_UNSET = object() + + +class DevOpsClient: + """Wraps the Azure DevOps Service Endpoint API for pipeline scan rules. + + Instantiate once per scan (alongside AzureClient) and share across all + Supply Chain rule modules that need Azure DevOps data. Every method logs + on failure and returns None so an unreachable or unconfigured Azure + DevOps organization never crashes the scan engine. + """ + + def __init__(self, organization_url: str, project: str, credential: Optional[Any] = None) -> None: + """ + Args: + organization_url: e.g. "https://dev.azure.com/my-org". + project: The Azure DevOps project name or ID to scan. + credential: A TokenCredential. Defaults to DefaultAzureCredential, + matching AzureClient's default. + """ + self.organization_url = organization_url + self.project = project + if credential is None: + from azure.identity import DefaultAzureCredential + + credential = DefaultAzureCredential() + self.credential = credential + self._service_endpoints_cache: Any = _UNSET + + def _get_connection(self) -> Any: + from azure.devops.connection import Connection + from azure.devops.credentials import OAuthTokenAuthentication + + access_token = self.credential.get_token(f"{AZURE_DEVOPS_RESOURCE_ID}/.default") + auth = OAuthTokenAuthentication(AZURE_DEVOPS_RESOURCE_ID, {"access_token": access_token.token}) + return Connection(base_url=self.organization_url, creds=auth) + + def get_service_endpoints(self) -> Optional[List[Any]]: + """Return pipeline service connections for the configured project. + + Cached for the lifetime of this client because both AZ-SC service + connection rules evaluate the same project-level collection. + + Returns: + A list (including an empty list) when Azure DevOps responds + successfully, or ``None`` when auth, permissions, or the SDK + prevent the collection from being evaluated. Callers must never + interpret ``None`` as a compliant result. + """ + if self._service_endpoints_cache is not _UNSET: + return self._service_endpoints_cache + + try: + connection = self._get_connection() + client = connection.clients_v7_1.get_service_endpoint_client() + self._service_endpoints_cache = list(client.get_service_endpoints(project=self.project)) + except Exception as exc: + logger.error("get_service_endpoints failed for project %s: %s", self.project, exc) + self._service_endpoints_cache = None + return self._service_endpoints_cache diff --git a/scanner/rules/az_sc_001.py b/scanner/rules/az_sc_001.py new file mode 100644 index 00000000..f24b7fc8 --- /dev/null +++ b/scanner/rules/az_sc_001.py @@ -0,0 +1,70 @@ +"""AZ-SC-001: Azure Container Registry admin user enabled.""" + +import logging +from typing import Any, Dict, List + +RULE_ID = "AZ-SC-001" +RULE_NAME = "Container Registry Admin User Enabled" +SEVERITY = "HIGH" +CATEGORY = "Supply Chain" +FRAMEWORKS = {"CIS": "TBD-SC-001", "NIST": "PR.AC-1", "ISO27001": "A.9.2.1", "SOC2": "CC6.1"} + +DESCRIPTION = ( + "The Azure Container Registry has the admin user enabled. The admin account is a single " + "shared, non-attributable credential that bypasses Azure RBAC entirely, so registry pushes " + "and pulls made with it cannot be tied to an individual identity or revoked without affecting " + "every other user of the same credential." +) + +REMEDIATION = ( + "Disable the admin user and authenticate to the registry with Azure AD identities or a " + "managed identity instead: az acr update --name --admin-enabled false" +) + +PLAYBOOK = "playbooks/cli/fix_az_sc_001.sh" + +logger = logging.getLogger(__name__) + + +def scan(azure_client: Any, subscription_id: str) -> List[Dict[str, Any]]: + """Detect Container Registries with the admin user enabled.""" + findings: List[Dict[str, Any]] = [] + + registries = azure_client.get_container_registries() + if registries is None: + logger.warning("%s: container registries could not be enumerated", RULE_ID) + return findings + + for registry in registries: + props = getattr(registry, "properties", None) + if props is None: + continue + + admin_enabled = getattr(props, "admin_user_enabled", None) + if admin_enabled is None: + logger.warning("%s: admin_user_enabled unknown for %s", RULE_ID, getattr(registry, "name", "?")) + continue + + if admin_enabled: + parsed = azure_client.parse_resource_id(getattr(registry, "id", "")) + findings.append( + { + "rule_id": RULE_ID, + "rule_name": RULE_NAME, + "severity": SEVERITY, + "category": CATEGORY, + "resource_id": getattr(registry, "id", ""), + "resource_name": getattr(registry, "name", ""), + "resource_type": "Microsoft.ContainerRegistry/registries", + "description": DESCRIPTION, + "remediation": REMEDIATION, + "playbook": PLAYBOOK, + "frameworks": FRAMEWORKS, + "metadata": { + "resource_group": parsed.get("resource_group", ""), + "admin_user_enabled": True, + }, + } + ) + + return findings diff --git a/scanner/rules/az_sc_002.py b/scanner/rules/az_sc_002.py new file mode 100644 index 00000000..f9433823 --- /dev/null +++ b/scanner/rules/az_sc_002.py @@ -0,0 +1,71 @@ +"""AZ-SC-002: Azure Container Registry allows public network access.""" + +import logging +from typing import Any, Dict, List + +from scanner.azure_client import enum_str + +RULE_ID = "AZ-SC-002" +RULE_NAME = "Container Registry Public Network Access Enabled" +SEVERITY = "HIGH" +CATEGORY = "Supply Chain" +FRAMEWORKS = {"CIS": "TBD-SC-002", "NIST": "PR.AC-5", "ISO27001": "A.13.1.1", "SOC2": "CC6.6"} + +DESCRIPTION = ( + "The Azure Container Registry is reachable from the public internet. A registry that holds " + "the container images an organization builds and deploys should only be reachable from " + "trusted networks, the same way source code and build systems are." +) + +REMEDIATION = ( + "Disable public network access and expose the registry through a private endpoint instead: " + "az acr update --name --public-network-enabled false" +) + +PLAYBOOK = "playbooks/cli/fix_az_sc_002.sh" + +logger = logging.getLogger(__name__) + + +def scan(azure_client: Any, subscription_id: str) -> List[Dict[str, Any]]: + """Detect Container Registries with public network access enabled.""" + findings: List[Dict[str, Any]] = [] + + registries = azure_client.get_container_registries() + if registries is None: + logger.warning("%s: container registries could not be enumerated", RULE_ID) + return findings + + for registry in registries: + props = getattr(registry, "properties", None) + if props is None: + continue + + public_access = enum_str(getattr(props, "public_network_access", None)) + if not public_access: + logger.warning("%s: public_network_access unknown for %s", RULE_ID, getattr(registry, "name", "?")) + continue + + if public_access.lower() == "enabled": + parsed = azure_client.parse_resource_id(getattr(registry, "id", "")) + findings.append( + { + "rule_id": RULE_ID, + "rule_name": RULE_NAME, + "severity": SEVERITY, + "category": CATEGORY, + "resource_id": getattr(registry, "id", ""), + "resource_name": getattr(registry, "name", ""), + "resource_type": "Microsoft.ContainerRegistry/registries", + "description": DESCRIPTION, + "remediation": REMEDIATION, + "playbook": PLAYBOOK, + "frameworks": FRAMEWORKS, + "metadata": { + "resource_group": parsed.get("resource_group", ""), + "public_network_access": public_access, + }, + } + ) + + return findings diff --git a/scanner/rules/az_sc_003.py b/scanner/rules/az_sc_003.py new file mode 100644 index 00000000..ff7bd9c3 --- /dev/null +++ b/scanner/rules/az_sc_003.py @@ -0,0 +1,71 @@ +"""AZ-SC-003: Azure Container Registry allows anonymous pull.""" + +import logging +from typing import Any, Dict, List + +RULE_ID = "AZ-SC-003" +RULE_NAME = "Container Registry Allows Anonymous Pull" +SEVERITY = "HIGH" +CATEGORY = "Supply Chain" +FRAMEWORKS = {"CIS": "TBD-SC-003", "NIST": "PR.AC-1", "ISO27001": "A.9.2.1", "SOC2": "CC6.1"} + +DESCRIPTION = ( + "The Azure Container Registry allows anonymous pull, so any client on the network can pull " + "every image in the registry without authenticating. Repository-scoped tokens cannot limit " + "this once it is enabled; the setting applies registry-wide. If this registry is intentionally " + "used for public OCI distribution, treat this finding as an accepted exception rather than a " + "defect." +) + +REMEDIATION = ( + "Disable anonymous pull unless the registry is deliberately used for public distribution: " + "az acr update --name --anonymous-pull-enabled false" +) + +PLAYBOOK = "playbooks/cli/fix_az_sc_003.sh" + +logger = logging.getLogger(__name__) + + +def scan(azure_client: Any, subscription_id: str) -> List[Dict[str, Any]]: + """Detect Container Registries with anonymous pull enabled.""" + findings: List[Dict[str, Any]] = [] + + registries = azure_client.get_container_registries() + if registries is None: + logger.warning("%s: container registries could not be enumerated", RULE_ID) + return findings + + for registry in registries: + props = getattr(registry, "properties", None) + if props is None: + continue + + anonymous_pull = getattr(props, "anonymous_pull_enabled", None) + if anonymous_pull is None: + logger.warning("%s: anonymous_pull_enabled unknown for %s", RULE_ID, getattr(registry, "name", "?")) + continue + + if anonymous_pull: + parsed = azure_client.parse_resource_id(getattr(registry, "id", "")) + findings.append( + { + "rule_id": RULE_ID, + "rule_name": RULE_NAME, + "severity": SEVERITY, + "category": CATEGORY, + "resource_id": getattr(registry, "id", ""), + "resource_name": getattr(registry, "name", ""), + "resource_type": "Microsoft.ContainerRegistry/registries", + "description": DESCRIPTION, + "remediation": REMEDIATION, + "playbook": PLAYBOOK, + "frameworks": FRAMEWORKS, + "metadata": { + "resource_group": parsed.get("resource_group", ""), + "anonymous_pull_enabled": True, + }, + } + ) + + return findings diff --git a/scanner/rules/az_sc_004.py b/scanner/rules/az_sc_004.py new file mode 100644 index 00000000..4d40fb10 --- /dev/null +++ b/scanner/rules/az_sc_004.py @@ -0,0 +1,91 @@ +"""AZ-SC-004: Azure Container Registry has no image retention or quarantine policy.""" + +import logging +from typing import Any, Dict, List + +RULE_ID = "AZ-SC-004" +RULE_NAME = "Container Registry Missing Retention or Quarantine Policy" +SEVERITY = "MEDIUM" +CATEGORY = "Supply Chain" +FRAMEWORKS = {"CIS": "TBD-SC-004", "NIST": "PR.IP-1", "ISO27001": "A.12.1.2", "SOC2": "CC7.1"} + +DESCRIPTION = ( + "The Azure Container Registry has no retention policy for untagged manifests, so stale and " + "orphaned images accumulate indefinitely, widening the pool of images that can be deployed. " + "On Premium-tier registries that also lack a quarantine policy, a newly pushed image is " + "pullable and deployable before any vulnerability scan has evaluated it." +) + +REMEDIATION = ( + "Enable a retention policy to purge untagged manifests after a defined window: " + "az acr config retention update --registry --status enabled --days 30. " + "On Premium-tier registries, also enable the quarantine policy so pushed images are held " + "until scanned." +) + +PLAYBOOK = "playbooks/cli/fix_az_sc_004.sh" + +logger = logging.getLogger(__name__) + +_PREMIUM_TIER = "premium" + + +def scan(azure_client: Any, subscription_id: str) -> List[Dict[str, Any]]: + """Detect Container Registries missing a retention policy, or (Premium only) a quarantine policy.""" + findings: List[Dict[str, Any]] = [] + + registries = azure_client.get_container_registries() + if registries is None: + logger.warning("%s: container registries could not be enumerated", RULE_ID) + return findings + + for registry in registries: + props = getattr(registry, "properties", None) + if props is None: + continue + + sku = getattr(registry, "sku", None) + tier = str(getattr(sku, "tier", "") or "").lower() if sku is not None else "" + is_premium = tier == _PREMIUM_TIER + + policies = getattr(props, "policies", None) + retention_status = None + quarantine_status = None + if policies is not None: + retention = getattr(policies, "retention_policy", None) + quarantine = getattr(policies, "quarantine_policy", None) + retention_status = getattr(retention, "status", None) if retention is not None else None + quarantine_status = getattr(quarantine, "status", None) if quarantine is not None else None + + retention_enabled = str(retention_status or "").lower() == "enabled" + quarantine_enabled = str(quarantine_status or "").lower() == "enabled" + + # Quarantine is a Premium-only feature; a Basic/Standard registry can + # never satisfy it, so only require it on Premium registries. + is_missing = not retention_enabled or (is_premium and not quarantine_enabled) + + if is_missing: + parsed = azure_client.parse_resource_id(getattr(registry, "id", "")) + findings.append( + { + "rule_id": RULE_ID, + "rule_name": RULE_NAME, + "severity": SEVERITY, + "category": CATEGORY, + "resource_id": getattr(registry, "id", ""), + "resource_name": getattr(registry, "name", ""), + "resource_type": "Microsoft.ContainerRegistry/registries", + "description": DESCRIPTION, + "remediation": REMEDIATION, + "playbook": PLAYBOOK, + "frameworks": FRAMEWORKS, + "metadata": { + "resource_group": parsed.get("resource_group", ""), + "sku_tier": tier, + "retention_policy_enabled": retention_enabled, + "quarantine_policy_enabled": quarantine_enabled if is_premium else None, + }, + } + ) + + return findings diff --git a/scanner/rules/az_sc_005.py b/scanner/rules/az_sc_005.py new file mode 100644 index 00000000..1c0230c8 --- /dev/null +++ b/scanner/rules/az_sc_005.py @@ -0,0 +1,85 @@ +"""AZ-SC-005: Terraform state storage container is publicly readable.""" + +import logging +import re +from typing import Any, Dict, List + +RULE_ID = "AZ-SC-005" +RULE_NAME = "Terraform State Storage Container Publicly Readable" +SEVERITY = "CRITICAL" +CATEGORY = "Supply Chain" +FRAMEWORKS = {"CIS": "TBD-SC-005", "NIST": "PR.AC-5", "ISO27001": "A.13.1.1", "SOC2": "CC6.6"} + +DESCRIPTION = ( + "A blob container that appears to hold Terraform remote state (matched by name) allows " + "public read access. Terraform state files commonly contain resource IDs, connection " + "strings, and in some provider configurations plaintext secrets. Public read access on the " + "state backend can expose the full infrastructure layout and any secrets it captured." +) + +REMEDIATION = ( + "Set the container's public access level to Private and confirm no anonymous read policy is " + "attached: az storage container set-permission --name --account-name " + "--public-access off" +) + +PLAYBOOK = "playbooks/cli/fix_az_sc_005.sh" + +logger = logging.getLogger(__name__) + +# Matches container names commonly used for a Terraform remote state backend, +# e.g. "tfstate", "terraform-state", "tf-state-prod". +_TFSTATE_NAME_PATTERN = re.compile(r"tf[-_]?state|terraform[-_]?state", re.IGNORECASE) + + +def scan(azure_client: Any, subscription_id: str) -> List[Dict[str, Any]]: + """Detect publicly readable blob containers that look like Terraform state backends.""" + findings: List[Dict[str, Any]] = [] + + for account in azure_client.get_storage_accounts(): + account_id = getattr(account, "id", "") + account_name = getattr(account, "name", "") + if not account_id or not account_name: + continue + + parsed = azure_client.parse_resource_id(account_id) + resource_group = parsed.get("resource_group", "") + if not resource_group: + continue + + containers = azure_client.get_blob_containers(resource_group, account_name) + if containers is None: + logger.warning("%s: blob containers unknown for %s", RULE_ID, account_name) + continue + + for container in containers: + container_name = getattr(container, "name", "") + if not _TFSTATE_NAME_PATTERN.search(container_name): + continue + + props = getattr(container, "container_properties", None) or container + public_access = str(getattr(props, "public_access", "") or "").lower() + if public_access in ("container", "blob"): + findings.append( + { + "rule_id": RULE_ID, + "rule_name": RULE_NAME, + "severity": SEVERITY, + "category": CATEGORY, + "resource_id": f"{account_id}/blobServices/default/containers/{container_name}", + "resource_name": f"{account_name}/{container_name}", + "resource_type": "Microsoft.Storage/storageAccounts/blobServices/containers", + "description": DESCRIPTION, + "remediation": REMEDIATION, + "playbook": PLAYBOOK, + "frameworks": FRAMEWORKS, + "metadata": { + "resource_group": resource_group, + "storage_account": account_name, + "container_name": container_name, + "public_access": public_access, + }, + } + ) + + return findings diff --git a/scanner/rules/az_sc_006.py b/scanner/rules/az_sc_006.py new file mode 100644 index 00000000..dec2cd4e --- /dev/null +++ b/scanner/rules/az_sc_006.py @@ -0,0 +1,91 @@ +"""AZ-SC-006: Terraform state storage account has no versioning or soft delete.""" + +import logging +import re +from typing import Any, Dict, List + +RULE_ID = "AZ-SC-006" +RULE_NAME = "Terraform State Storage Account Missing Versioning or Soft Delete" +SEVERITY = "HIGH" +CATEGORY = "Supply Chain" +FRAMEWORKS = {"CIS": "TBD-SC-006", "NIST": "PR.IP-4", "ISO27001": "A.12.3.1", "SOC2": "A1.2"} + +DESCRIPTION = ( + "A storage account holding a container that appears to be a Terraform remote state backend " + "has neither blob versioning nor blob soft delete enabled. Azure does not support these " + "settings per container, only account-wide. Without either, an overwritten or accidentally " + "deleted state file cannot be recovered, which can leave Terraform unable to reconcile its " + "understanding of deployed infrastructure with reality." +) + +REMEDIATION = ( + "Enable blob versioning and soft delete on the storage account: " + "az storage account blob-service-properties update --account-name " + "--enable-versioning true --enable-delete-retention true --delete-retention-days 30" +) + +PLAYBOOK = "playbooks/cli/fix_az_sc_006.sh" + +logger = logging.getLogger(__name__) + +_TFSTATE_NAME_PATTERN = re.compile(r"tf[-_]?state|terraform[-_]?state", re.IGNORECASE) + + +def scan(azure_client: Any, subscription_id: str) -> List[Dict[str, Any]]: + """Detect Terraform state storage accounts missing versioning or soft delete.""" + findings: List[Dict[str, Any]] = [] + + for account in azure_client.get_storage_accounts(): + account_id = getattr(account, "id", "") + account_name = getattr(account, "name", "") + if not account_id or not account_name: + continue + + parsed = azure_client.parse_resource_id(account_id) + resource_group = parsed.get("resource_group", "") + if not resource_group: + continue + + containers = azure_client.get_blob_containers(resource_group, account_name) + if containers is None: + logger.warning("%s: blob containers unknown for %s", RULE_ID, account_name) + continue + + has_state_container = any( + _TFSTATE_NAME_PATTERN.search(getattr(container, "name", "") or "") for container in containers + ) + if not has_state_container: + continue + + blob_service = azure_client.get_blob_service_properties(resource_group, account_name) + if blob_service is None: + logger.warning("%s: blob service properties unknown for %s", RULE_ID, account_name) + continue + + versioning_enabled = bool(getattr(blob_service, "is_versioning_enabled", False)) + retention_policy = getattr(blob_service, "delete_retention_policy", None) + soft_delete_enabled = bool(getattr(retention_policy, "enabled", False)) if retention_policy else False + + if not (versioning_enabled or soft_delete_enabled): + findings.append( + { + "rule_id": RULE_ID, + "rule_name": RULE_NAME, + "severity": SEVERITY, + "category": CATEGORY, + "resource_id": account_id, + "resource_name": account_name, + "resource_type": "Microsoft.Storage/storageAccounts", + "description": DESCRIPTION, + "remediation": REMEDIATION, + "playbook": PLAYBOOK, + "frameworks": FRAMEWORKS, + "metadata": { + "resource_group": resource_group, + "versioning_enabled": versioning_enabled, + "soft_delete_enabled": soft_delete_enabled, + }, + } + ) + + return findings diff --git a/scanner/rules/az_sc_007.py b/scanner/rules/az_sc_007.py new file mode 100644 index 00000000..e41bdba8 --- /dev/null +++ b/scanner/rules/az_sc_007.py @@ -0,0 +1,75 @@ +"""AZ-SC-007: Pipeline service connection scoped to the whole subscription.""" + +import logging +from typing import Any, Dict, List + +RULE_ID = "AZ-SC-007" +RULE_NAME = "Pipeline Service Connection Scoped to Subscription" +SEVERITY = "HIGH" +CATEGORY = "Supply Chain" +FRAMEWORKS = {"CIS": "TBD-SC-007", "NIST": "PR.AC-4", "ISO27001": "A.9.2.3", "SOC2": "CC6.1"} + +DESCRIPTION = ( + "An Azure DevOps service connection is scoped to the entire subscription rather than a " + "single resource group. A service principal deploying a single App Service does not need " + "Contributor on the whole subscription; every pipeline that uses this connection inherits " + "subscription-wide access, including pipelines that only need to touch one resource group." +) + +REMEDIATION = ( + "Re-create the service connection scoped to the resource group each pipeline actually needs " + "instead of the whole subscription. See Azure DevOps: Project Settings > Service connections > " + "New service connection > Azure Resource Manager > Resource Group." +) + +PLAYBOOK = "playbooks/cli/fix_az_sc_007.sh" + +logger = logging.getLogger(__name__) + + +def scan(azure_client: Any, subscription_id: str) -> List[Dict[str, Any]]: + """Detect Azure DevOps service connections scoped to the whole subscription.""" + findings: List[Dict[str, Any]] = [] + + devops_client = getattr(azure_client, "devops_client", None) + if devops_client is None: + return findings + + endpoints = devops_client.get_service_endpoints() + if endpoints is None: + logger.warning("%s: Azure DevOps service endpoints could not be enumerated", RULE_ID) + return findings + + for endpoint in endpoints: + endpoint_type = getattr(endpoint, "type", "") or "" + if endpoint_type.lower() != "azurerm": + continue + + data = getattr(endpoint, "data", None) or {} + scope_level = str(data.get("scopeLevel", "")).lower() + + if scope_level == "subscription": + endpoint_id = getattr(endpoint, "id", "") + endpoint_name = getattr(endpoint, "name", "") + findings.append( + { + "rule_id": RULE_ID, + "rule_name": RULE_NAME, + "severity": SEVERITY, + "category": CATEGORY, + "resource_id": f"azuredevops:serviceendpoint/{endpoint_id}", + "resource_name": endpoint_name, + "resource_type": "AzureDevOps/ServiceEndpoint", + "description": DESCRIPTION, + "remediation": REMEDIATION, + "playbook": PLAYBOOK, + "frameworks": FRAMEWORKS, + "metadata": { + "scope_level": scope_level, + "is_shared_with_other_projects": bool(getattr(endpoint, "is_shared", False)), + "subscription_id": data.get("subscriptionId", ""), + }, + } + ) + + return findings diff --git a/scanner/rules/az_sc_008.py b/scanner/rules/az_sc_008.py new file mode 100644 index 00000000..42856aa0 --- /dev/null +++ b/scanner/rules/az_sc_008.py @@ -0,0 +1,81 @@ +"""AZ-SC-008: Pipeline service connection uses a password/secret instead of a federated credential.""" + +import logging +from typing import Any, Dict, List + +RULE_ID = "AZ-SC-008" +RULE_NAME = "Pipeline Service Connection Uses Password Instead of Federated Credential" +SEVERITY = "MEDIUM" +CATEGORY = "Supply Chain" +FRAMEWORKS = {"CIS": "TBD-SC-008", "NIST": "PR.AC-1", "ISO27001": "A.9.4.3", "SOC2": "CC6.1"} + +DESCRIPTION = ( + "An Azure DevOps service connection authenticates with a stored service principal secret " + "instead of a secretless authentication scheme (workload identity federation or a managed " + "identity). A secretless scheme has nothing to rotate or leak. A stored secret expires after " + "a fixed period, must be rotated manually, and can be exposed through pipeline logs or " + "variable misconfiguration in the meantime." +) + +REMEDIATION = ( + "Re-create the service connection using workload identity federation or a managed identity " + "instead of a service principal secret. See: az devops service-endpoint azurerm create with " + "--service-principal-type federated, or the equivalent option in the Azure DevOps UI." +) + +PLAYBOOK = "playbooks/cli/fix_az_sc_008.sh" + +logger = logging.getLogger(__name__) + +# Both schemes are secretless: workload identity federation (OIDC) and managed +# identity. Only a plain "ServicePrincipal" scheme relies on a stored secret. +_SECRETLESS_SCHEMES = {"workloadidentityfederation", "managedserviceidentity"} + + +def scan(azure_client: Any, subscription_id: str) -> List[Dict[str, Any]]: + """Detect Azure DevOps service connections using a password/secret scheme.""" + findings: List[Dict[str, Any]] = [] + + devops_client = getattr(azure_client, "devops_client", None) + if devops_client is None: + return findings + + endpoints = devops_client.get_service_endpoints() + if endpoints is None: + logger.warning("%s: Azure DevOps service endpoints could not be enumerated", RULE_ID) + return findings + + for endpoint in endpoints: + endpoint_type = getattr(endpoint, "type", "") or "" + if endpoint_type.lower() != "azurerm": + continue + + authorization = getattr(endpoint, "authorization", None) + scheme = str(getattr(authorization, "scheme", "") or "").lower() if authorization else "" + if not scheme: + logger.warning("%s: authorization scheme unknown for %s", RULE_ID, getattr(endpoint, "name", "?")) + continue + + if scheme not in _SECRETLESS_SCHEMES: + endpoint_id = getattr(endpoint, "id", "") + endpoint_name = getattr(endpoint, "name", "") + findings.append( + { + "rule_id": RULE_ID, + "rule_name": RULE_NAME, + "severity": SEVERITY, + "category": CATEGORY, + "resource_id": f"azuredevops:serviceendpoint/{endpoint_id}", + "resource_name": endpoint_name, + "resource_type": "AzureDevOps/ServiceEndpoint", + "description": DESCRIPTION, + "remediation": REMEDIATION, + "playbook": PLAYBOOK, + "frameworks": FRAMEWORKS, + "metadata": { + "authorization_scheme": scheme, + }, + } + ) + + return findings diff --git a/scripts/check_dco.py b/scripts/check_dco.py new file mode 100644 index 00000000..1e5eb8a6 --- /dev/null +++ b/scripts/check_dco.py @@ -0,0 +1,68 @@ +"""Require a Developer Certificate of Origin sign-off on each PR commit.""" + +import re +import subprocess +import sys +from typing import Iterable + + +SIGNOFF = re.compile(r"^Signed-off-by:\s+.+\s+<[^<>@\s]+@[^<>\s]+>$", re.IGNORECASE | re.MULTILINE) + + +def has_signoff(message: str) -> bool: + """Return whether a commit message contains a well-formed DCO trailer.""" + return SIGNOFF.search(message) is not None + + +def commits_between(base: str, head: str) -> list[str]: + """Return commits introduced between the pull request base and head. + + Excludes merge commits: a `git merge origin/dev` inside a long-running PR + branch produces a commit with Git's default merge message and no + Signed-off-by trailer, through no fault of the author's own commits. + GitHub's own DCO app skips merge commits for the same reason. + """ + output = subprocess.check_output( + ["git", "rev-list", "--reverse", "--no-merges", f"{base}..{head}"], + text=True, + ) + return [item for item in output.splitlines() if item] + + +def commit_message(commit: str) -> str: + """Read one commit message without interpreting its contents as a command.""" + return subprocess.check_output( + ["git", "show", "--no-patch", "--format=%B", commit], + text=True, + ) + + +def unsigned_commits(commits: Iterable[str]) -> list[str]: + """Return commit IDs that lack a valid Signed-off-by trailer.""" + return [commit for commit in commits if not has_signoff(commit_message(commit))] + + +def main() -> int: + if len(sys.argv) != 3: + print("Usage: check_dco.py ", file=sys.stderr) + return 2 + + commits = commits_between(sys.argv[1], sys.argv[2]) + if not commits: + print("No pull request commits found.", file=sys.stderr) + return 1 + + missing = unsigned_commits(commits) + if missing: + print("The following commits lack a valid DCO Signed-off-by trailer:", file=sys.stderr) + for commit in missing: + print(f" {commit}", file=sys.stderr) + print("Recreate or amend them with: git commit -s", file=sys.stderr) + return 1 + + print(f"DCO sign-off verified for {len(commits)} commit(s).") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/helpers/mock_azure.py b/tests/helpers/mock_azure.py index 7cb3aa20..75a6cc9e 100644 --- a/tests/helpers/mock_azure.py +++ b/tests/helpers/mock_azure.py @@ -85,6 +85,11 @@ def __init__(self) -> None: self._applications: Optional[List[Dict[str, Any]]] = [] self._managed_identity_principals: Optional[List[Dict[str, Any]]] = [] self._subscription_role_assignments: Optional[List[Any]] = [] + self._container_registries: Optional[List[Any]] = [] + self._blob_containers: Dict[Tuple[str, str], Optional[List[Any]]] = {} + self._blob_service_properties: Dict[Tuple[str, str], Optional[Any]] = {} + # None by default, matching AzureClient.devops_client's "not configured" state. + self.devops_client: Optional[Any] = None # Some rules read azure_client.subscription_id when constructing an # SDK management client inside scan() (e.g. AZ-NET-007..010). self.subscription_id = "00000000-0000-0000-0000-000000000001" @@ -122,6 +127,34 @@ def set_subscription_role_assignments(self, assignments: Optional[List[Any]]) -> def get_subscription_role_assignments(self) -> Optional[List[Any]]: return self._subscription_role_assignments + def set_container_registries(self, registries: Optional[List[Any]]) -> "MockAzureClient": + """Configure Container Registry inventory; ``None`` represents an API failure.""" + self._container_registries = registries + return self + + def get_container_registries(self) -> Optional[List[Any]]: + return self._container_registries + + def set_blob_containers( + self, resource_group: str, account_name: str, containers: Optional[List[Any]] + ) -> "MockAzureClient": + """Configure per-account blob container listing; ``None`` represents an API failure.""" + self._blob_containers[(resource_group, account_name)] = containers + return self + + def get_blob_containers(self, resource_group: str, account_name: str) -> Optional[List[Any]]: + return self._blob_containers.get((resource_group, account_name), None) + + def set_blob_service_properties( + self, resource_group: str, account_name: str, properties: Optional[Any] + ) -> "MockAzureClient": + """Configure per-account blob service properties; ``None`` represents an API failure.""" + self._blob_service_properties[(resource_group, account_name)] = properties + return self + + def get_blob_service_properties(self, resource_group: str, account_name: str) -> Optional[Any]: + return self._blob_service_properties.get((resource_group, account_name), None) + def set_network_security_groups(self, nsgs: List[Any]) -> "MockAzureClient": self._network_security_groups = nsgs return self diff --git a/tests/test_azure_client_management.py b/tests/test_azure_client_management.py index a0f65526..179fb6fe 100644 --- a/tests/test_azure_client_management.py +++ b/tests/test_azure_client_management.py @@ -94,3 +94,62 @@ def test_vm_extensions_normalize_sdk_page_and_failure(client): assert client.get_vm_extensions("rg", "vm")[0].name == "agent" constructor.return_value.virtual_machine_extensions.list.side_effect = RuntimeError("denied") assert client.get_vm_extensions("rg", "vm") is None + + +def test_get_container_registries_returns_results_and_caches(client): + with patch("azure.mgmt.containerregistry.ContainerRegistryManagementClient") as constructor: + constructor.return_value.registries.list.return_value = [SimpleNamespace(name="acr1")] + result = client.get_container_registries() + assert result is not None + assert [r.name for r in result] == ["acr1"] + + # cached: second call must not hit the SDK again + constructor.return_value.registries.list.side_effect = RuntimeError("should not be called") + assert [r.name for r in client.get_container_registries()] == ["acr1"] + + +def test_get_container_registries_failure_returns_none(client): + with patch("azure.mgmt.containerregistry.ContainerRegistryManagementClient") as constructor: + constructor.return_value.registries.list.side_effect = RuntimeError("denied") + assert client.get_container_registries() is None + + +def test_get_blob_containers_and_service_properties(client): + with patch("scanner.azure_client.StorageManagementClient") as constructor: + constructor.return_value.blob_containers.list.return_value = [SimpleNamespace(name="tfstate")] + result = client.get_blob_containers("rg", "sa1") + assert result is not None + assert result[0].name == "tfstate" + + constructor.return_value.blob_containers.list.side_effect = RuntimeError("denied") + assert client.get_blob_containers("rg", "sa1") is None + + constructor.return_value.blob_services.get_service_properties.return_value = SimpleNamespace( + is_versioning_enabled=True + ) + props = client.get_blob_service_properties("rg", "sa1") + assert props.is_versioning_enabled is True + + constructor.return_value.blob_services.get_service_properties.side_effect = RuntimeError("denied") + assert client.get_blob_service_properties("rg", "sa1") is None + + +def test_devops_client_not_built_without_env_vars(monkeypatch): + monkeypatch.delenv("AZURE_DEVOPS_ORG_URL", raising=False) + monkeypatch.delenv("AZURE_DEVOPS_PROJECT", raising=False) + from scanner.azure_client import AzureClient + + fresh_client = AzureClient("sub-1", credential=MagicMock()) + assert fresh_client.devops_client is None + + +def test_devops_client_built_when_env_vars_present(monkeypatch): + monkeypatch.setenv("AZURE_DEVOPS_ORG_URL", "https://dev.azure.com/test-org") + monkeypatch.setenv("AZURE_DEVOPS_PROJECT", "test-project") + from scanner.azure_client import AzureClient + from scanner.devops_client import DevOpsClient + + fresh_client = AzureClient("sub-1", credential=MagicMock()) + assert isinstance(fresh_client.devops_client, DevOpsClient) + assert fresh_client.devops_client.organization_url == "https://dev.azure.com/test-org" + assert fresh_client.devops_client.project == "test-project" diff --git a/tests/test_dco_check.py b/tests/test_dco_check.py new file mode 100644 index 00000000..c062c29c --- /dev/null +++ b/tests/test_dco_check.py @@ -0,0 +1,36 @@ +"""Tests for the dependency-free DCO enforcement helper.""" + +from unittest.mock import patch + +from scripts.check_dco import commits_between, has_signoff, unsigned_commits + + +def test_has_signoff_accepts_standard_dco_trailer(): + assert has_signoff("feat: change\n\nSigned-off-by: Tanvir Farhad \n") + + +def test_has_signoff_rejects_missing_or_malformed_trailer(): + assert not has_signoff("feat: unsigned change") + assert not has_signoff("Signed-off-by: anonymous") + assert not has_signoff("Signed-off-by: Name ") + + +def test_unsigned_commits_checks_each_commit(): + messages = { + "a": "fix: one\n\nSigned-off-by: A User ", + "b": "fix: two", + } + with patch("scripts.check_dco.commit_message", side_effect=messages.get): + assert unsigned_commits(["a", "b"]) == ["b"] + + +def test_commits_between_excludes_merge_commits(): + """A `git merge origin/dev` inside a PR branch has no Signed-off-by + trailer and isn't the author's own commit — it must never be checked, + or a legitimate PR gets blocked for merging the base branch in.""" + with patch("scripts.check_dco.subprocess.check_output", return_value="abc123\ndef456\n") as mock_run: + result = commits_between("base-sha", "head-sha") + + assert result == ["abc123", "def456"] + called_args = mock_run.call_args.args[0] + assert "--no-merges" in called_args diff --git a/tests/test_devops_client.py b/tests/test_devops_client.py new file mode 100644 index 00000000..58f2f9c7 --- /dev/null +++ b/tests/test_devops_client.py @@ -0,0 +1,54 @@ +"""Direct tests for DevOpsClient and its failure states.""" + +from unittest.mock import MagicMock, patch + +import pytest + +from scanner.devops_client import DevOpsClient + + +@pytest.fixture +def client(): + return DevOpsClient("https://dev.azure.com/test-org", "test-project", credential=MagicMock()) + + +def test_get_service_endpoints_returns_results_and_caches(client): + client.credential.get_token.return_value = MagicMock(token="fake-token") + + with patch("azure.devops.connection.Connection") as conn_ctor: + fake_conn = MagicMock() + conn_ctor.return_value = fake_conn + fake_conn.clients_v7_1.get_service_endpoint_client.return_value.get_service_endpoints.return_value = [ + MagicMock(name="ep1") + ] + result = client.get_service_endpoints() + assert result is not None + assert len(result) == 1 + + # cached: second call must not rebuild the connection + conn_ctor.side_effect = RuntimeError("should not be called") + assert client.get_service_endpoints() is result + + +def test_get_service_endpoints_auth_failure_returns_none(): + client = DevOpsClient("https://dev.azure.com/test-org", "test-project", credential=MagicMock()) + client.credential.get_token.side_effect = RuntimeError("auth failed") + assert client.get_service_endpoints() is None + + +def test_get_service_endpoints_api_failure_returns_none(client): + client.credential.get_token.return_value = MagicMock(token="fake-token") + with patch("azure.devops.connection.Connection") as conn_ctor: + fake_conn = MagicMock() + conn_ctor.return_value = fake_conn + fake_conn.clients_v7_1.get_service_endpoint_client.return_value.get_service_endpoints.side_effect = ( + RuntimeError("denied") + ) + assert client.get_service_endpoints() is None + + +def test_default_credential_used_when_none_provided(): + with patch("azure.identity.DefaultAzureCredential") as cred_ctor: + cred_ctor.return_value = MagicMock() + client = DevOpsClient("https://dev.azure.com/test-org", "test-project") + assert client.credential is cred_ctor.return_value diff --git a/tests/test_rules_supply_chain.py b/tests/test_rules_supply_chain.py new file mode 100644 index 00000000..05db472a --- /dev/null +++ b/tests/test_rules_supply_chain.py @@ -0,0 +1,294 @@ +"""Rule regression tests for the Supply Chain rules AZ-SC-001 .. AZ-SC-008.""" + +from types import SimpleNamespace + +import scanner.rules.az_sc_001 as az_sc_001 +import scanner.rules.az_sc_002 as az_sc_002 +import scanner.rules.az_sc_003 as az_sc_003 +import scanner.rules.az_sc_004 as az_sc_004 +import scanner.rules.az_sc_005 as az_sc_005 +import scanner.rules.az_sc_006 as az_sc_006 +import scanner.rules.az_sc_007 as az_sc_007 +import scanner.rules.az_sc_008 as az_sc_008 +from tests.helpers.mock_azure import make_resource + +_SUB = "00000000-0000-0000-0000-000000000001" +_RG = "rg-test" + + +def _acr_id(name): + return f"/subscriptions/{_SUB}/resourceGroups/{_RG}/providers/Microsoft.ContainerRegistry/registries/{name}" + + +def _sa_id(name): + return f"/subscriptions/{_SUB}/resourceGroups/{_RG}/providers/Microsoft.Storage/storageAccounts/{name}" + + +def _make_registry( + name, admin_enabled=False, public_access="Disabled", anonymous_pull=False, policies=None, sku_tier=None +): + props = make_resource( + admin_user_enabled=admin_enabled, + public_network_access=public_access, + anonymous_pull_enabled=anonymous_pull, + policies=policies, + ) + sku = make_resource(tier=sku_tier) if sku_tier is not None else None + return make_resource(id=_acr_id(name), name=name, properties=props, sku=sku) + + +def _make_policies(retention_status="enabled", quarantine_status="enabled"): + return make_resource( + retention_policy=make_resource(status=retention_status), + quarantine_policy=make_resource(status=quarantine_status), + ) + + +def _make_container(name, public_access="None"): + return make_resource(name=name, container_properties=make_resource(public_access=public_access)) + + +# ── AZ-SC-001: ACR admin user enabled ─────────────────────────────────────── + + +def test_sc_001_admin_enabled_returns_finding(mock_azure, subscription_id): + mock_azure.set_container_registries([_make_registry("acr1", admin_enabled=True)]) + findings = az_sc_001.scan(mock_azure, subscription_id) + assert len(findings) == 1 + assert findings[0]["rule_id"] == "AZ-SC-001" + assert findings[0]["severity"] == "HIGH" + assert findings[0]["category"] == "Supply Chain" + + +def test_sc_001_admin_disabled_returns_no_findings(mock_azure, subscription_id): + mock_azure.set_container_registries([_make_registry("acr1", admin_enabled=False)]) + assert az_sc_001.scan(mock_azure, subscription_id) == [] + + +def test_sc_001_inventory_failure_returns_no_findings(mock_azure, subscription_id): + mock_azure.set_container_registries(None) + assert az_sc_001.scan(mock_azure, subscription_id) == [] + + +# ── AZ-SC-002: ACR public network access ──────────────────────────────────── + + +def test_sc_002_public_access_returns_finding(mock_azure, subscription_id): + mock_azure.set_container_registries([_make_registry("acr1", public_access="Enabled")]) + findings = az_sc_002.scan(mock_azure, subscription_id) + assert len(findings) == 1 + assert findings[0]["rule_id"] == "AZ-SC-002" + + +def test_sc_002_private_access_returns_no_findings(mock_azure, subscription_id): + mock_azure.set_container_registries([_make_registry("acr1", public_access="Disabled")]) + assert az_sc_002.scan(mock_azure, subscription_id) == [] + + +# ── AZ-SC-003: ACR anonymous pull ─────────────────────────────────────────── + + +def test_sc_003_anonymous_pull_returns_finding(mock_azure, subscription_id): + mock_azure.set_container_registries([_make_registry("acr1", anonymous_pull=True)]) + findings = az_sc_003.scan(mock_azure, subscription_id) + assert len(findings) == 1 + assert findings[0]["rule_id"] == "AZ-SC-003" + + +def test_sc_003_anonymous_pull_disabled_returns_no_findings(mock_azure, subscription_id): + mock_azure.set_container_registries([_make_registry("acr1", anonymous_pull=False)]) + assert az_sc_003.scan(mock_azure, subscription_id) == [] + + +# ── AZ-SC-004: ACR missing retention/quarantine policy ────────────────────── + + +def test_sc_004_missing_retention_returns_finding(mock_azure, subscription_id): + registry = _make_registry("acr1", policies=_make_policies(retention_status="disabled")) + mock_azure.set_container_registries([registry]) + findings = az_sc_004.scan(mock_azure, subscription_id) + assert len(findings) == 1 + assert findings[0]["rule_id"] == "AZ-SC-004" + + +def test_sc_004_basic_tier_missing_quarantine_is_compliant(mock_azure, subscription_id): + """Quarantine is Premium-only; a Basic-tier registry must not be flagged for + lacking a feature it cannot enable, as long as retention is configured.""" + registry = _make_registry( + "acr1", sku_tier="Basic", policies=_make_policies(retention_status="enabled", quarantine_status="disabled") + ) + mock_azure.set_container_registries([registry]) + assert az_sc_004.scan(mock_azure, subscription_id) == [] + + +def test_sc_004_premium_tier_missing_quarantine_returns_finding(mock_azure, subscription_id): + """On a Premium registry, quarantine is available, so lacking it must be flagged.""" + registry = _make_registry( + "acr1", + sku_tier="Premium", + policies=_make_policies(retention_status="enabled", quarantine_status="disabled"), + ) + mock_azure.set_container_registries([registry]) + findings = az_sc_004.scan(mock_azure, subscription_id) + assert len(findings) == 1 + assert findings[0]["metadata"]["quarantine_policy_enabled"] is False + + +def test_sc_004_premium_tier_both_policies_enabled_returns_no_findings(mock_azure, subscription_id): + registry = _make_registry("acr1", sku_tier="Premium", policies=_make_policies()) + mock_azure.set_container_registries([registry]) + assert az_sc_004.scan(mock_azure, subscription_id) == [] + + +def test_sc_004_missing_policies_object_returns_finding(mock_azure, subscription_id): + """A registry with no `policies` block at all has no retention policy and must be flagged.""" + registry = _make_registry("acr1", policies=None) + mock_azure.set_container_registries([registry]) + findings = az_sc_004.scan(mock_azure, subscription_id) + assert len(findings) == 1 + + +# ── AZ-SC-005: Terraform state container publicly readable ───────────────── + + +def test_sc_005_public_tfstate_container_returns_finding(mock_azure, subscription_id): + account = make_resource(id=_sa_id("sa1"), name="sa1") + mock_azure.set_storage_accounts([account]) + mock_azure.set_blob_containers(_RG, "sa1", [_make_container("tfstate-prod", public_access="Container")]) + findings = az_sc_005.scan(mock_azure, subscription_id) + assert len(findings) == 1 + assert findings[0]["rule_id"] == "AZ-SC-005" + assert findings[0]["severity"] == "CRITICAL" + + +def test_sc_005_private_tfstate_container_returns_no_findings(mock_azure, subscription_id): + account = make_resource(id=_sa_id("sa1"), name="sa1") + mock_azure.set_storage_accounts([account]) + mock_azure.set_blob_containers(_RG, "sa1", [_make_container("tfstate-prod", public_access="None")]) + assert az_sc_005.scan(mock_azure, subscription_id) == [] + + +def test_sc_005_non_tfstate_container_name_ignored(mock_azure, subscription_id): + account = make_resource(id=_sa_id("sa1"), name="sa1") + mock_azure.set_storage_accounts([account]) + mock_azure.set_blob_containers(_RG, "sa1", [_make_container("app-uploads", public_access="Container")]) + assert az_sc_005.scan(mock_azure, subscription_id) == [] + + +def test_sc_005_container_listing_failure_returns_no_findings(mock_azure, subscription_id): + account = make_resource(id=_sa_id("sa1"), name="sa1") + mock_azure.set_storage_accounts([account]) + mock_azure.set_blob_containers(_RG, "sa1", None) + assert az_sc_005.scan(mock_azure, subscription_id) == [] + + +# ── AZ-SC-006: Terraform state account missing versioning/soft delete ────── + + +def test_sc_006_no_versioning_or_soft_delete_returns_finding(mock_azure, subscription_id): + account = make_resource(id=_sa_id("sa1"), name="sa1") + mock_azure.set_storage_accounts([account]) + mock_azure.set_blob_containers(_RG, "sa1", [_make_container("terraform-state")]) + blob_service = make_resource( + is_versioning_enabled=False, + delete_retention_policy=make_resource(enabled=False), + ) + mock_azure.set_blob_service_properties(_RG, "sa1", blob_service) + findings = az_sc_006.scan(mock_azure, subscription_id) + assert len(findings) == 1 + assert findings[0]["rule_id"] == "AZ-SC-006" + + +def test_sc_006_versioning_enabled_returns_no_findings(mock_azure, subscription_id): + account = make_resource(id=_sa_id("sa1"), name="sa1") + mock_azure.set_storage_accounts([account]) + mock_azure.set_blob_containers(_RG, "sa1", [_make_container("terraform-state")]) + blob_service = make_resource( + is_versioning_enabled=True, + delete_retention_policy=make_resource(enabled=False), + ) + mock_azure.set_blob_service_properties(_RG, "sa1", blob_service) + assert az_sc_006.scan(mock_azure, subscription_id) == [] + + +def test_sc_006_no_state_container_returns_no_findings(mock_azure, subscription_id): + account = make_resource(id=_sa_id("sa1"), name="sa1") + mock_azure.set_storage_accounts([account]) + mock_azure.set_blob_containers(_RG, "sa1", [_make_container("app-uploads")]) + assert az_sc_006.scan(mock_azure, subscription_id) == [] + + +# ── AZ-SC-007 / AZ-SC-008: Azure DevOps service connections ──────────────── + + +class _FakeDevOpsClient: + def __init__(self, endpoints): + self._endpoints = endpoints + + def get_service_endpoints(self): + return self._endpoints + + +def _make_endpoint(name, scope_level="ResourceGroup", is_shared=False, scheme="WorkloadIdentityFederation"): + return SimpleNamespace( + id=f"endpoint-{name}", + name=name, + type="AzureRM", + is_shared=is_shared, + data={"scopeLevel": scope_level, "subscriptionId": _SUB}, + authorization=SimpleNamespace(scheme=scheme), + ) + + +def test_sc_007_subscription_scoped_returns_finding(mock_azure, subscription_id): + mock_azure.devops_client = _FakeDevOpsClient([_make_endpoint("conn1", scope_level="Subscription")]) + findings = az_sc_007.scan(mock_azure, subscription_id) + assert len(findings) == 1 + assert findings[0]["rule_id"] == "AZ-SC-007" + + +def test_sc_007_subscription_scoped_not_shared_still_returns_finding(mock_azure, subscription_id): + """Scope is the risk, not cross-project sharing (is_shared) - a subscription-scoped + connection is over-privileged whether or not it is shared with other projects.""" + mock_azure.devops_client = _FakeDevOpsClient([_make_endpoint("conn1", scope_level="Subscription", is_shared=False)]) + findings = az_sc_007.scan(mock_azure, subscription_id) + assert len(findings) == 1 + + +def test_sc_007_resource_group_scoped_returns_no_findings(mock_azure, subscription_id): + mock_azure.devops_client = _FakeDevOpsClient([_make_endpoint("conn1", scope_level="ResourceGroup")]) + assert az_sc_007.scan(mock_azure, subscription_id) == [] + + +def test_sc_007_devops_not_configured_returns_no_findings(mock_azure, subscription_id): + mock_azure.devops_client = None + assert az_sc_007.scan(mock_azure, subscription_id) == [] + + +def test_sc_007_endpoint_listing_failure_returns_no_findings(mock_azure, subscription_id): + mock_azure.devops_client = _FakeDevOpsClient(None) + assert az_sc_007.scan(mock_azure, subscription_id) == [] + + +def test_sc_008_password_based_returns_finding(mock_azure, subscription_id): + mock_azure.devops_client = _FakeDevOpsClient([_make_endpoint("conn1", scheme="ServicePrincipal")]) + findings = az_sc_008.scan(mock_azure, subscription_id) + assert len(findings) == 1 + assert findings[0]["rule_id"] == "AZ-SC-008" + + +def test_sc_008_federated_returns_no_findings(mock_azure, subscription_id): + mock_azure.devops_client = _FakeDevOpsClient([_make_endpoint("conn1", scheme="WorkloadIdentityFederation")]) + assert az_sc_008.scan(mock_azure, subscription_id) == [] + + +def test_sc_008_managed_identity_returns_no_findings(mock_azure, subscription_id): + """Managed identity is a second secretless scheme distinct from workload + identity federation and must not be flagged as a stored-secret connection.""" + mock_azure.devops_client = _FakeDevOpsClient([_make_endpoint("conn1", scheme="ManagedServiceIdentity")]) + assert az_sc_008.scan(mock_azure, subscription_id) == [] + + +def test_sc_008_devops_not_configured_returns_no_findings(mock_azure, subscription_id): + mock_azure.devops_client = None + assert az_sc_008.scan(mock_azure, subscription_id) == []