[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M71GR1WXFQJ0EWWTED4SBFWA":3,"skill-same:01M71GR1WXFQJ0EWWTED4SBFWA":99},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":28,"publishedAt":49,"linkOnly":50,"markdownContent":51,"markdownBody":52,"frontMatter":53,"refName":72,"commitSha":73,"skillDirectory":74,"forksCount":14,"repositoryHtmlUrl":75,"repositoryHomepageUrl":6,"ownerHtmlUrl":76,"ownerBlogUrl":6,"ownerDescription":77,"updatedAt":78,"install":79,"resources":92},"01M71GR1WXFQJ0EWWTED4SBFWA","api-posture-audit",null,"Implement API Security Posture Management to continuously discover, classify, and score APIs based on risk while enforcing security policies across the API lifecycle.","DCx7C5\u002Fai-marketplace","DCx7C5","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F42419559?v=4","01M71C01G2AZV3NTNGWAWSHJPP","DC","01M71C01GQW6G50S2BYMS7PP3E",0,"MIT","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fweb-application\u002Fapi\u002Fposture\u002Faudit\u002FSKILL.md",[18,23],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000010","后端与接口","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":26,"taxonomyTypeDesc":27},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48],"api","audit","api posture audit","security","api-governance","read","api-inventory","api-discovery","classify","de","across","monitoring","scoring","Bash","continuous-monitoring","cybersecurity","api-security","inventory","cm","discover","2026-11-10 10:12:30",false,"---\nname: api-posture-audit\ndescription: Implement API Security Posture Management to continuously discover, classify, and score APIs based on risk while enforcing security policies across the API lifecycle.\ndomain: cybersecurity\nsubdomain: api-security\ntags:\n- api-security\n- aspm\n- api-posture-management\n- api-discovery\n- risk-scoring\n- api-governance\n- continuous-monitoring\n- api-inventory\nnist_csf:\n- PR.PS-01\n- ID.RA-01\n- PR.DS-10\n- DE.CM-01\nmodel: sonnet\nmaxTurns: 20\ntools: [Read, Bash, Glob, Grep]\nmitre_attack:\n- T1082\ncapec: []\n---\n\n# Implementing API Security Posture Management\n\n## Overview\n\nAPI Security Posture Management (API-SPM) provides continuous visibility into an organization's API attack surface by automatically discovering, classifying, and risk-scoring all APIs including internal, external, partner, and shadow endpoints. Unlike point-in-time testing tools, API-SPM operates continuously to detect configuration drift, policy violations, missing security controls, sensitive data exposure, and compliance gaps. It aggregates findings from DAST, SAST, SCA, and runtime monitoring tools to provide a unified view of API risk posture across the organization.\n\n\n## When to Use\n\n- When deploying or configuring implementing api security posture management capabilities in your environment\n- When establishing security controls aligned to compliance requirements\n- When building or improving security architecture for this domain\n- When conducting security assessments that require this implementation\n\n## Prerequisites\n\n- API gateway with traffic logging (Kong, AWS API Gateway, Apigee, Envoy)\n- OpenAPI specifications for documented APIs\n- SIEM or log aggregation platform (Splunk, Elastic)\n- CI\u002FCD pipeline access for shift-left integration\n- Cloud provider APIs for infrastructure discovery\n- Python 3.8+ for custom posture assessment tooling\n\n## Core Components\n\n### 1. API Discovery and Inventory\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"API Security Posture Management Engine\n\nContinuously discovers, classifies, and risk-scores APIs\nto maintain a comprehensive security posture inventory.\n\"\"\"\n\nimport json\nimport re\nimport hashlib\nfrom datetime import datetime, timedelta\nfrom typing import Dict, List, Optional, Set\nfrom dataclasses import dataclass, field\nfrom enum import Enum\n\nclass APIClassification(Enum):\n    EXTERNAL = \"external\"\n    INTERNAL = \"internal\"\n    PARTNER = \"partner\"\n    SHADOW = \"shadow\"\n    DEPRECATED = \"deprecated\"\n\nclass RiskLevel(Enum):\n    CRITICAL = 4\n    HIGH = 3\n    MEDIUM = 2\n    LOW = 1\n    INFO = 0\n\n@dataclass\nclass SecurityControl:\n    name: str\n    present: bool\n    required: bool\n    severity: RiskLevel\n    details: str = \"\"\n\n@dataclass\nclass APIEndpoint:\n    api_id: str\n    method: str\n    path: str\n    service_name: str\n    classification: APIClassification\n    owner: Optional[str] = None\n    version: Optional[str] = None\n    first_discovered: str = \"\"\n    last_seen: str = \"\"\n    documented: bool = False\n    security_controls: List[SecurityControl] = field(default_factory=list)\n    risk_score: float = 0.0\n    sensitive_data_types: Set[str] = field(default_factory=set)\n    compliance_tags: Set[str] = field(default_factory=set)\n    traffic_volume_daily: int = 0\n\nclass APIPostureManager:\n    SENSITIVE_PATTERNS = {\n        \"ssn\": re.compile(r'\\b\\d{3}-\\d{2}-\\d{4}\\b'),\n        \"credit_card\": re.compile(r'\\b\\d{4}[- ]?\\d{4}[- ]?\\d{4}[- ]?\\d{4}\\b'),\n        \"email\": re.compile(r'\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b'),\n        \"api_key\": re.compile(r'\\b[A-Za-z0-9]{32,}\\b'),\n        \"jwt\": re.compile(r'eyJ[A-Za-z0-9_-]+\\.eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+'),\n        \"phone\": re.compile(r'\\b\\+?1?\\d{10,15}\\b'),\n    }\n\n    def __init__(self):\n        self.inventory: Dict[str, APIEndpoint] = {}\n        self.policy_rules: List[dict] = []\n\n    def generate_api_id(self, method: str, path: str, service: str) -> str:\n        raw = f\"{service}:{method}:{path}\"\n        return hashlib.sha256(raw.encode()).hexdigest()[:16]\n\n    def register_api(self, method: str, path: str, service_name: str,\n                     classification: APIClassification,\n                     documented: bool = False, owner: str = None) -> APIEndpoint:\n        api_id = self.generate_api_id(method, path, service_name)\n        now = datetime.now().isoformat()\n\n        if api_id in self.inventory:\n            endpoint = self.inventory[api_id]\n            endpoint.last_seen = now\n            return endpoint\n\n        endpoint = APIEndpoint(\n            api_id=api_id,\n            method=method,\n            path=path,\n            service_name=service_name,\n            classification=classification,\n            owner=owner,\n            first_discovered=now,\n            last_seen=now,\n            documented=documented\n        )\n        self.inventory[api_id] = endpoint\n        return endpoint\n\n    def assess_security_controls(self, endpoint: APIEndpoint,\n                                  traffic_sample: dict) -> List[SecurityControl]:\n        \"\"\"Evaluate security controls present on an API endpoint.\"\"\"\n        controls = []\n\n        # Authentication check\n        has_auth = any(h in traffic_sample.get('request_headers', {})\n                      for h in ['Authorization', 'X-API-Key', 'Cookie'])\n        controls.append(SecurityControl(\n            name=\"authentication\",\n            present=has_auth,\n            required=True,\n            severity=RiskLevel.CRITICAL,\n            details=\"No authentication mechanism detected\" if not has_auth else \"Authentication present\"\n        ))\n\n        # TLS\u002FHTTPS check\n        is_https = traffic_sample.get('scheme', '').lower() == 'https'\n        controls.append(SecurityControl(\n            name=\"transport_encryption\",\n            present=is_https,\n            required=True,\n            severity=RiskLevel.CRITICAL,\n            details=\"API accessible over HTTP without TLS\" if not is_https else \"HTTPS enforced\"\n        ))\n\n        # Rate limiting check\n        has_rate_limit = any(h.startswith('X-RateLimit') or h == 'Retry-After'\n                           for h in traffic_sample.get('response_headers', {}).keys())\n        controls.append(SecurityControl(\n            name=\"rate_limiting\",\n            present=has_rate_limit,\n            required=True,\n            severity=RiskLevel.HIGH,\n            details=\"No rate limiting headers detected\" if not has_rate_limit else \"Rate limiting active\"\n        ))\n\n        # CORS policy check\n        cors_origin = traffic_sample.get('response_headers', {}).get('Access-Control-Allow-Origin', '')\n        has_strict_cors = cors_origin and cors_origin != '*'\n        controls.append(SecurityControl(\n            name=\"cors_policy\",\n            present=has_strict_cors,\n            required=endpoint.classification == APIClassification.EXTERNAL,\n            severity=RiskLevel.HIGH if cors_origin == '*' else RiskLevel.MEDIUM,\n            details=f\"CORS origin: {cors_origin}\" if cors_origin else \"No CORS headers\"\n        ))\n\n        # Security headers\n        sec_headers = traffic_sample.get('response_headers', {})\n        required_headers = {\n            'X-Content-Type-Options': 'nosniff',\n            'Strict-Transport-Security': None,\n            'X-Frame-Options': None,\n            'Cache-Control': 'no-store',\n        }\n        missing = [h for h in required_headers if h not in sec_headers]\n        controls.append(SecurityControl(\n            name=\"security_headers\",\n            present=len(missing) == 0,\n            required=True,\n            severity=RiskLevel.MEDIUM,\n            details=f\"Missing headers: {', '.join(missing)}\" if missing else \"All security headers present\"\n        ))\n\n        # Input validation (check for schema validation errors in logs)\n        has_validation = traffic_sample.get('has_schema_validation', False)\n        controls.append(SecurityControl(\n            name=\"input_validation\",\n            present=has_validation,\n            required=True,\n            severity=RiskLevel.HIGH,\n            details=\"No schema validation detected\" if not has_validation else \"Input validation active\"\n        ))\n\n        endpoint.security_controls = controls\n        return controls\n\n    def calculate_risk_score(self, endpoint: APIEndpoint) -> float:\n        \"\"\"Calculate a composite risk score (0-100) for an API endpoint.\"\"\"\n        score = 0.0\n        max_score = 0.0\n\n        # Security controls scoring\n        for control in endpoint.security_controls:\n            weight = control.severity.value * 5\n            max_score += weight\n            if not control.present and control.required:\n                score += weight\n\n        # Classification risk multiplier\n        classification_weights = {\n            APIClassification.EXTERNAL: 1.5,\n            APIClassification.PARTNER: 1.3,\n            APIClassification.SHADOW: 2.0,\n            APIClassification.DEPRECATED: 1.8,\n            APIClassification.INTERNAL: 1.0,\n        }\n        multiplier = classification_weights.get(endpoint.classification, 1.0)\n\n        # Documentation penalty\n        if not endpoint.documented:\n            score += 10\n\n        # Sensitive data penalty\n        score += len(endpoint.sensitive_data_types) * 5\n\n        # Normalize to 0-100\n        if max_score > 0:\n            normalized = min(100, (score \u002F max_score) * 100 * multiplier)\n        else:\n            normalized = 0\n\n        endpoint.risk_score = round(normalized, 1)\n        return endpoint.risk_score\n\n    def generate_posture_report(self) -> dict:\n        \"\"\"Generate organization-wide API security posture report.\"\"\"\n        total = len(self.inventory)\n        if total == 0:\n            return {\"error\": \"No APIs in inventory\"}\n\n        risk_distribution = {level.name: 0 for level in RiskLevel}\n        classification_counts = {c.value: 0 for c in APIClassification}\n        undocumented = 0\n        missing_auth = 0\n        missing_tls = 0\n\n        for endpoint in self.inventory.values():\n            self.calculate_risk_score(endpoint)\n\n            if endpoint.risk_score >= 75:\n                risk_distribution[\"CRITICAL\"] += 1\n            elif endpoint.risk_score >= 50:\n                risk_distribution[\"HIGH\"] += 1\n            elif endpoint.risk_score >= 25:\n                risk_distribution[\"MEDIUM\"] += 1\n            else:\n                risk_distribution[\"LOW\"] += 1\n\n            classification_counts[endpoint.classification.value] += 1\n\n            if not endpoint.documented:\n                undocumented += 1\n\n            for control in endpoint.security_controls:\n                if control.name == \"authentication\" and not control.present:\n                    missing_auth += 1\n                if control.name == \"transport_encryption\" and not control.present:\n                    missing_tls += 1\n\n        avg_risk = sum(e.risk_score for e in self.inventory.values()) \u002F total\n\n        return {\n            \"report_date\": datetime.now().isoformat(),\n            \"total_apis\": total,\n            \"average_risk_score\": round(avg_risk, 1),\n            \"risk_distribution\": risk_distribution,\n            \"classification\": classification_counts,\n            \"undocumented_apis\": undocumented,\n            \"missing_authentication\": missing_auth,\n            \"missing_tls\": missing_tls,\n            \"top_risks\": sorted(\n                [{\"api_id\": e.api_id, \"method\": e.method, \"path\": e.path,\n                  \"service\": e.service_name, \"risk_score\": e.risk_score,\n                  \"classification\": e.classification.value}\n                 for e in self.inventory.values()],\n                key=lambda x: x[\"risk_score\"],\n                reverse=True\n            )[:20]\n        }\n```\n\n### 2. Policy Enforcement\n\nDefine and enforce security policies across all APIs:\n\n```yaml\n# api-security-policies.yaml\npolicies:\n  - name: require-authentication\n    description: All external APIs must require authentication\n    scope:\n      classification: [external, partner]\n    rule:\n      control: authentication\n      required: true\n    severity: critical\n    remediation: \"Add OAuth2, API key, or JWT authentication\"\n\n  - name: enforce-tls\n    description: All APIs must use HTTPS\n    scope:\n      classification: [external, internal, partner]\n    rule:\n      control: transport_encryption\n      required: true\n    severity: critical\n    remediation: \"Configure TLS certificates and redirect HTTP to HTTPS\"\n\n  - name: require-rate-limiting\n    description: External APIs must implement rate limiting\n    scope:\n      classification: [external]\n    rule:\n      control: rate_limiting\n      required: true\n    severity: high\n    remediation: \"Configure rate limiting at API gateway level\"\n\n  - name: no-wildcard-cors\n    description: APIs must not use wildcard CORS origins\n    scope:\n      classification: [external]\n    rule:\n      control: cors_policy\n      condition: \"origin != '*'\"\n    severity: high\n    remediation: \"Specify explicit allowed origins in CORS configuration\"\n\n  - name: documentation-required\n    description: All APIs must have OpenAPI documentation\n    scope:\n      classification: [external, partner]\n    rule:\n      documented: true\n    severity: medium\n    remediation: \"Create and publish OpenAPI specification\"\n\n  - name: deprecation-sunset\n    description: Deprecated APIs must have sunset headers\n    scope:\n      classification: [deprecated]\n    rule:\n      header_present: \"Sunset\"\n    severity: medium\n    remediation: \"Add Sunset header with planned removal date\"\n```\n\n## Continuous Monitoring Dashboard Metrics\n\n| Metric | Description | Target |\n|--------|------------|--------|\n| API Discovery Coverage | % of APIs with documentation | > 95% |\n| Average Risk Score | Mean risk score across all APIs | \u003C 25 |\n| Critical Findings | Number of critical-risk APIs | 0 |\n| Shadow API Count | Undocumented\u002Funmanaged APIs | 0 |\n| Authentication Coverage | % of APIs with auth controls | 100% |\n| TLS Coverage | % of APIs using HTTPS | 100% |\n| Policy Compliance | % of APIs meeting all policies | > 90% |\n| Mean Time to Remediate | Average days to fix findings | \u003C 7 days |\n\n## References\n\n- OX Security ASPM Guide 2025: https:\u002F\u002Fwww.ox.security\u002Fblog\u002Fapplication-security-posture-management-aspm\u002F\n- IBM ASPM Overview: https:\u002F\u002Fwww.ibm.com\u002Fthink\u002Ftopics\u002Faspm\n- StackHawk Best ASPM Tools: https:\u002F\u002Fwww.stackhawk.com\u002Fblog\u002Fbest-aspm-tools\u002F\n- AppSentinels API Security Posture Management: https:\u002F\u002Fappsentinels.ai\u002Fblog\u002Fapi-security-posture-management-from-reactive-protection-to-continuous-governance\u002F\n- Palo Alto Networks ASPM: https:\u002F\u002Fwww.paloaltonetworks.com\u002Fcyberpedia\u002Faspm-application-security-posture-management\n","# Implementing API Security Posture Management\n\n## Overview\n\nAPI Security Posture Management (API-SPM) provides continuous visibility into an organization's API attack surface by automatically discovering, classifying, and risk-scoring all APIs including internal, external, partner, and shadow endpoints. Unlike point-in-time testing tools, API-SPM operates continuously to detect configuration drift, policy violations, missing security controls, sensitive data exposure, and compliance gaps. It aggregates findings from DAST, SAST, SCA, and runtime monitoring tools to provide a unified view of API risk posture across the organization.\n\n\n## When to Use\n\n- When deploying or configuring implementing api security posture management capabilities in your environment\n- When establishing security controls aligned to compliance requirements\n- When building or improving security architecture for this domain\n- When conducting security assessments that require this implementation\n\n## Prerequisites\n\n- API gateway with traffic logging (Kong, AWS API Gateway, Apigee, Envoy)\n- OpenAPI specifications for documented APIs\n- SIEM or log aggregation platform (Splunk, Elastic)\n- CI\u002FCD pipeline access for shift-left integration\n- Cloud provider APIs for infrastructure discovery\n- Python 3.8+ for custom posture assessment tooling\n\n## Core Components\n\n### 1. API Discovery and Inventory\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"API Security Posture Management Engine\n\nContinuously discovers, classifies, and risk-scores APIs\nto maintain a comprehensive security posture inventory.\n\"\"\"\n\nimport json\nimport re\nimport hashlib\nfrom datetime import datetime, timedelta\nfrom typing import Dict, List, Optional, Set\nfrom dataclasses import dataclass, field\nfrom enum import Enum\n\nclass APIClassification(Enum):\n    EXTERNAL = \"external\"\n    INTERNAL = \"internal\"\n    PARTNER = \"partner\"\n    SHADOW = \"shadow\"\n    DEPRECATED = \"deprecated\"\n\nclass RiskLevel(Enum):\n    CRITICAL = 4\n    HIGH = 3\n    MEDIUM = 2\n    LOW = 1\n    INFO = 0\n\n@dataclass\nclass SecurityControl:\n    name: str\n    present: bool\n    required: bool\n    severity: RiskLevel\n    details: str = \"\"\n\n@dataclass\nclass APIEndpoint:\n    api_id: str\n    method: str\n    path: str\n    service_name: str\n    classification: APIClassification\n    owner: Optional[str] = None\n    version: Optional[str] = None\n    first_discovered: str = \"\"\n    last_seen: str = \"\"\n    documented: bool = False\n    security_controls: List[SecurityControl] = field(default_factory=list)\n    risk_score: float = 0.0\n    sensitive_data_types: Set[str] = field(default_factory=set)\n    compliance_tags: Set[str] = field(default_factory=set)\n    traffic_volume_daily: int = 0\n\nclass APIPostureManager:\n    SENSITIVE_PATTERNS = {\n        \"ssn\": re.compile(r'\\b\\d{3}-\\d{2}-\\d{4}\\b'),\n        \"credit_card\": re.compile(r'\\b\\d{4}[- ]?\\d{4}[- ]?\\d{4}[- ]?\\d{4}\\b'),\n        \"email\": re.compile(r'\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b'),\n        \"api_key\": re.compile(r'\\b[A-Za-z0-9]{32,}\\b'),\n        \"jwt\": re.compile(r'eyJ[A-Za-z0-9_-]+\\.eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+'),\n        \"phone\": re.compile(r'\\b\\+?1?\\d{10,15}\\b'),\n    }\n\n    def __init__(self):\n        self.inventory: Dict[str, APIEndpoint] = {}\n        self.policy_rules: List[dict] = []\n\n    def generate_api_id(self, method: str, path: str, service: str) -> str:\n        raw = f\"{service}:{method}:{path}\"\n        return hashlib.sha256(raw.encode()).hexdigest()[:16]\n\n    def register_api(self, method: str, path: str, service_name: str,\n                     classification: APIClassification,\n                     documented: bool = False, owner: str = None) -> APIEndpoint:\n        api_id = self.generate_api_id(method, path, service_name)\n        now = datetime.now().isoformat()\n\n        if api_id in self.inventory:\n            endpoint = self.inventory[api_id]\n            endpoint.last_seen = now\n            return endpoint\n\n        endpoint = APIEndpoint(\n            api_id=api_id,\n            method=method,\n            path=path,\n            service_name=service_name,\n            classification=classification,\n            owner=owner,\n            first_discovered=now,\n            last_seen=now,\n            documented=documented\n        )\n        self.inventory[api_id] = endpoint\n        return endpoint\n\n    def assess_security_controls(self, endpoint: APIEndpoint,\n                                  traffic_sample: dict) -> List[SecurityControl]:\n        \"\"\"Evaluate security controls present on an API endpoint.\"\"\"\n        controls = []\n\n        # Authentication check\n        has_auth = any(h in traffic_sample.get('request_headers', {})\n                      for h in ['Authorization', 'X-API-Key', 'Cookie'])\n        controls.append(SecurityControl(\n            name=\"authentication\",\n            present=has_auth,\n            required=True,\n            severity=RiskLevel.CRITICAL,\n            details=\"No authentication mechanism detected\" if not has_auth else \"Authentication present\"\n        ))\n\n        # TLS\u002FHTTPS check\n        is_https = traffic_sample.get('scheme', '').lower() == 'https'\n        controls.append(SecurityControl(\n            name=\"transport_encryption\",\n            present=is_https,\n            required=True,\n            severity=RiskLevel.CRITICAL,\n            details=\"API accessible over HTTP without TLS\" if not is_https else \"HTTPS enforced\"\n        ))\n\n        # Rate limiting check\n        has_rate_limit = any(h.startswith('X-RateLimit') or h == 'Retry-After'\n                           for h in traffic_sample.get('response_headers', {}).keys())\n        controls.append(SecurityControl(\n            name=\"rate_limiting\",\n            present=has_rate_limit,\n            required=True,\n            severity=RiskLevel.HIGH,\n            details=\"No rate limiting headers detected\" if not has_rate_limit else \"Rate limiting active\"\n        ))\n\n        # CORS policy check\n        cors_origin = traffic_sample.get('response_headers', {}).get('Access-Control-Allow-Origin', '')\n        has_strict_cors = cors_origin and cors_origin != '*'\n        controls.append(SecurityControl(\n            name=\"cors_policy\",\n            present=has_strict_cors,\n            required=endpoint.classification == APIClassification.EXTERNAL,\n            severity=RiskLevel.HIGH if cors_origin == '*' else RiskLevel.MEDIUM,\n            details=f\"CORS origin: {cors_origin}\" if cors_origin else \"No CORS headers\"\n        ))\n\n        # Security headers\n        sec_headers = traffic_sample.get('response_headers', {})\n        required_headers = {\n            'X-Content-Type-Options': 'nosniff',\n            'Strict-Transport-Security': None,\n            'X-Frame-Options': None,\n            'Cache-Control': 'no-store',\n        }\n        missing = [h for h in required_headers if h not in sec_headers]\n        controls.append(SecurityControl(\n            name=\"security_headers\",\n            present=len(missing) == 0,\n            required=True,\n            severity=RiskLevel.MEDIUM,\n            details=f\"Missing headers: {', '.join(missing)}\" if missing else \"All security headers present\"\n        ))\n\n        # Input validation (check for schema validation errors in logs)\n        has_validation = traffic_sample.get('has_schema_validation', False)\n        controls.append(SecurityControl(\n            name=\"input_validation\",\n            present=has_validation,\n            required=True,\n            severity=RiskLevel.HIGH,\n            details=\"No schema validation detected\" if not has_validation else \"Input validation active\"\n        ))\n\n        endpoint.security_controls = controls\n        return controls\n\n    def calculate_risk_score(self, endpoint: APIEndpoint) -> float:\n        \"\"\"Calculate a composite risk score (0-100) for an API endpoint.\"\"\"\n        score = 0.0\n        max_score = 0.0\n\n        # Security controls scoring\n        for control in endpoint.security_controls:\n            weight = control.severity.value * 5\n            max_score += weight\n            if not control.present and control.required:\n                score += weight\n\n        # Classification risk multiplier\n        classification_weights = {\n            APIClassification.EXTERNAL: 1.5,\n            APIClassification.PARTNER: 1.3,\n            APIClassification.SHADOW: 2.0,\n            APIClassification.DEPRECATED: 1.8,\n            APIClassification.INTERNAL: 1.0,\n        }\n        multiplier = classification_weights.get(endpoint.classification, 1.0)\n\n        # Documentation penalty\n        if not endpoint.documented:\n            score += 10\n\n        # Sensitive data penalty\n        score += len(endpoint.sensitive_data_types) * 5\n\n        # Normalize to 0-100\n        if max_score > 0:\n            normalized = min(100, (score \u002F max_score) * 100 * multiplier)\n        else:\n            normalized = 0\n\n        endpoint.risk_score = round(normalized, 1)\n        return endpoint.risk_score\n\n    def generate_posture_report(self) -> dict:\n        \"\"\"Generate organization-wide API security posture report.\"\"\"\n        total = len(self.inventory)\n        if total == 0:\n            return {\"error\": \"No APIs in inventory\"}\n\n        risk_distribution = {level.name: 0 for level in RiskLevel}\n        classification_counts = {c.value: 0 for c in APIClassification}\n        undocumented = 0\n        missing_auth = 0\n        missing_tls = 0\n\n        for endpoint in self.inventory.values():\n            self.calculate_risk_score(endpoint)\n\n            if endpoint.risk_score >= 75:\n                risk_distribution[\"CRITICAL\"] += 1\n            elif endpoint.risk_score >= 50:\n                risk_distribution[\"HIGH\"] += 1\n            elif endpoint.risk_score >= 25:\n                risk_distribution[\"MEDIUM\"] += 1\n            else:\n                risk_distribution[\"LOW\"] += 1\n\n            classification_counts[endpoint.classification.value] += 1\n\n            if not endpoint.documented:\n                undocumented += 1\n\n            for control in endpoint.security_controls:\n                if control.name == \"authentication\" and not control.present:\n                    missing_auth += 1\n                if control.name == \"transport_encryption\" and not control.present:\n                    missing_tls += 1\n\n        avg_risk = sum(e.risk_score for e in self.inventory.values()) \u002F total\n\n        return {\n            \"report_date\": datetime.now().isoformat(),\n            \"total_apis\": total,\n            \"average_risk_score\": round(avg_risk, 1),\n            \"risk_distribution\": risk_distribution,\n            \"classification\": classification_counts,\n            \"undocumented_apis\": undocumented,\n            \"missing_authentication\": missing_auth,\n            \"missing_tls\": missing_tls,\n            \"top_risks\": sorted(\n                [{\"api_id\": e.api_id, \"method\": e.method, \"path\": e.path,\n                  \"service\": e.service_name, \"risk_score\": e.risk_score,\n                  \"classification\": e.classification.value}\n                 for e in self.inventory.values()],\n                key=lambda x: x[\"risk_score\"],\n                reverse=True\n            )[:20]\n        }\n```\n\n### 2. Policy Enforcement\n\nDefine and enforce security policies across all APIs:\n\n```yaml\n# api-security-policies.yaml\npolicies:\n  - name: require-authentication\n    description: All external APIs must require authentication\n    scope:\n      classification: [external, partner]\n    rule:\n      control: authentication\n      required: true\n    severity: critical\n    remediation: \"Add OAuth2, API key, or JWT authentication\"\n\n  - name: enforce-tls\n    description: All APIs must use HTTPS\n    scope:\n      classification: [external, internal, partner]\n    rule:\n      control: transport_encryption\n      required: true\n    severity: critical\n    remediation: \"Configure TLS certificates and redirect HTTP to HTTPS\"\n\n  - name: require-rate-limiting\n    description: External APIs must implement rate limiting\n    scope:\n      classification: [external]\n    rule:\n      control: rate_limiting\n      required: true\n    severity: high\n    remediation: \"Configure rate limiting at API gateway level\"\n\n  - name: no-wildcard-cors\n    description: APIs must not use wildcard CORS origins\n    scope:\n      classification: [external]\n    rule:\n      control: cors_policy\n      condition: \"origin != '*'\"\n    severity: high\n    remediation: \"Specify explicit allowed origins in CORS configuration\"\n\n  - name: documentation-required\n    description: All APIs must have OpenAPI documentation\n    scope:\n      classification: [external, partner]\n    rule:\n      documented: true\n    severity: medium\n    remediation: \"Create and publish OpenAPI specification\"\n\n  - name: deprecation-sunset\n    description: Deprecated APIs must have sunset headers\n    scope:\n      classification: [deprecated]\n    rule:\n      header_present: \"Sunset\"\n    severity: medium\n    remediation: \"Add Sunset header with planned removal date\"\n```\n\n## Continuous Monitoring Dashboard Metrics\n\n| Metric | Description | Target |\n|--------|------------|--------|\n| API Discovery Coverage | % of APIs with documentation | > 95% |\n| Average Risk Score | Mean risk score across all APIs | \u003C 25 |\n| Critical Findings | Number of critical-risk APIs | 0 |\n| Shadow API Count | Undocumented\u002Funmanaged APIs | 0 |\n| Authentication Coverage | % of APIs with auth controls | 100% |\n| TLS Coverage | % of APIs using HTTPS | 100% |\n| Policy Compliance | % of APIs meeting all policies | > 90% |\n| Mean Time to Remediate | Average days to fix findings | \u003C 7 days |\n\n## References\n\n- OX Security ASPM Guide 2025: https:\u002F\u002Fwww.ox.security\u002Fblog\u002Fapplication-security-posture-management-aspm\u002F\n- IBM ASPM Overview: https:\u002F\u002Fwww.ibm.com\u002Fthink\u002Ftopics\u002Faspm\n- StackHawk Best ASPM Tools: https:\u002F\u002Fwww.stackhawk.com\u002Fblog\u002Fbest-aspm-tools\u002F\n- AppSentinels API Security Posture Management: https:\u002F\u002Fappsentinels.ai\u002Fblog\u002Fapi-security-posture-management-from-reactive-protection-to-continuous-governance\u002F\n- Palo Alto Networks ASPM: https:\u002F\u002Fwww.paloaltonetworks.com\u002Fcyberpedia\u002Faspm-application-security-posture-management\n",{"name":5,"tags":54,"capec":58,"model":59,"tools":60,"domain":44,"maxTurns":64,"nist_csf":65,"subdomain":45,"description":7,"mitre_attack":70},[45,55,56,36,57,33,43,35],"aspm","api-posture-management","risk-scoring",[],"sonnet",[61,42,62,63],"Read","Glob","Grep",20,[66,67,68,69],"PR.PS-01","ID.RA-01","PR.DS-10","DE.CM-01",[71],"T1082","main","a91f1293287ffa9f4f1b8f486cd6e835a1568c84","skills\u002Fweb-application\u002Fapi\u002Fposture\u002Faudit","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace","https:\u002F\u002Fgithub.com\u002FDCx7C5","#Python","2026-09-01 11:21:00",{"source":8,"skillName":5,"commands":80,"prompt":90,"zipAvailable":91},[81,84,87],{"tool":82,"command":83},"npx","npx skills add DCx7C5\u002Fai-marketplace --skill api-posture-audit",{"tool":85,"command":86},"bunx","bunx skills add DCx7C5\u002Fai-marketplace --skill api-posture-audit",{"tool":88,"command":89},"pnpm","pnpm dlx skills add DCx7C5\u002Fai-marketplace --skill api-posture-audit","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fweb-application\u002Fapi\u002Fposture\u002Faudit\u002FSKILL.md",true,[93],{"path":94,"resourceType":95,"resourceTypeDesc":96,"sizeBytes":97,"sourceHtmlUrl":98},"index.json","REFERENCE","参考文档",648,"https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fweb-application\u002Fapi\u002Fposture\u002Faudit\u002Findex.json",[100,123,143,164,186,201],{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":49},"01M71HAPZ01KQ30RKTB0FFSQ05","services-wmi-persistence-detect","Detect WMI event subscription persistence by enumerating ActiveScriptEventConsumer, CommandLineEventConsumer, and permanent subscriptions in the WMI repository.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fservices\u002Fwmi\u002Fpersistence\u002Fdetect\u002FSKILL.md",[],[107,108,109,110,111,38,47,112,113,114,115,116,117,118,119,120,121,44,122],"services","detect","services wmi persistence detect","wmi","persistence","process","activescript","event","subscriptions","commandline-consumer","repository","subscription","event-subscription","t1546.003","forensics","process-forensics",{"skillNo":124,"name":125,"nameZh":6,"description":126,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":127,"categories":128,"keywords":129,"publishedAt":49},"01M71HAK6JTTTS229T17WJMMCG","services-wmi-exec-exploit","Perform lateral movement across Windows networks using WMI-based remote execution techniques including Impacket wmiexec.py, CrackMapExec, and native WMI commands for stealthy post-exploitation during red team engagements.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fservices\u002Fwmi\u002Fexec\u002Fexploit\u002FSKILL.md",[],[130,107,131,110,132,133,134,44,42,135,136,39,137,138,38,139,140,34,141,142],"exploit","services wmi exec exploit","exec","remote","traffic","analysis","team","crackmapexec","native","command","lateral movement","lateral-movement","Impacket",{"skillNo":144,"name":145,"nameZh":6,"description":146,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":147,"categories":148,"keywords":149,"publishedAt":49},"01M71HAG6MHKNQV8KDZKMT4886","registry-artifact-extract","Extract and analyze Windows Registry hives to uncover user activity, installed software, autostart entries, and evidence of system compromise.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fregistry\u002Fartifact\u002Fextract\u002FSKILL.md",[],[150,151,152,153,154,155,44,42,156,135,157,158,38,34,159,160,161,162,163,59],"artifact","registry","registry artifact extract","extract","evidence-collection","artifact-analysis","collection","analyze","uncover","software","activity","digital-forensics","windows-registry","regripper",{"skillNo":165,"name":166,"nameZh":6,"description":167,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":168,"categories":169,"keywords":170,"publishedAt":49},"01M71HACR4A8XTWTTSXK4124AA","processes-token-impersonate-detect","Detect Windows token impersonation and privilege abuse including SeImpersonatePrivilege exploitation via Potato attacks and token stealing techniques.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Ftoken\u002Fimpersonate\u002Fdetect\u002FSKILL.md",[],[108,171,172,173,174,175,176,47,177,44,122,178,179,180,181,182,183,184,185,38],"processes token impersonate detect","token","processes","attacks","windows","escalation","techniques","privilege-escalation","seimpersonate","token-impersonation","printspoofer","exploitation","potato","impersonation","via",{"skillNo":187,"name":188,"nameZh":6,"description":189,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":190,"categories":191,"keywords":192,"publishedAt":49},"01M71HAABSB4Z6QFSXEG00R4RK","processes-thread-injection-detect","Detect Windows thread injection techniques including CreateRemoteThread, QueueUserAPC, NtCreateThreadEx, and thread hijacking via process memory analysis.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Fthread\u002Finjection\u002Fdetect\u002FSKILL.md",[],[193,194,108,195,173,175,196,47,197,177,44,122,135,29,198,199,200,185,38,112],"thread","processes thread injection detect","injection","memory","process-injection","apc-injection","thread-injection","nt-api",{"skillNo":202,"name":203,"nameZh":6,"description":204,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":205,"categories":206,"keywords":207,"publishedAt":49},"01M71HA7H311V5G14WMX58HQSS","processes-hollow-technique-detect","Detect process hollowing (RunPE) by identifying processes with mismatched image paths between PEB and VAD tree, or unmapped PE headers in memory.","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fwindows\u002Fprocesses\u002Fhollow\u002Ftechnique\u002Fdetect\u002FSKILL.md",[],[208,108,173,209,196,47,210,211,44,122,212,213,214,215,216,217,38,112,218,219],"processes hollow technique detect","tree","memory-forensics","process-hollow","peb","runpe","image","pe-header","in memory","with","mismatched","headers"]