[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M750WZEQBC6SW9YVMA7EG1N7":3,"skill-same:01M750WZEQBC6SW9YVMA7EG1N7":73},{"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":16,"sourceHtmlUrl":17,"categories":18,"keywords":19,"publishedAt":20,"linkOnly":21,"markdownContent":22,"markdownBody":23,"frontMatter":24,"refName":37,"commitSha":38,"skillDirectory":5,"forksCount":14,"repositoryHtmlUrl":39,"repositoryHomepageUrl":6,"ownerHtmlUrl":40,"ownerBlogUrl":41,"ownerDescription":6,"updatedAt":42,"install":43,"resources":56},"01M750WZEQBC6SW9YVMA7EG1N7","implementing-api-security-posture-management",null,"Implement API Security Posture Management to continuously discover, classify, and score APIs based on risk while enforcing security policies across the API lifecycle.","SamuelChien\u002Fmega-skills-collection","SamuelChien","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F4652114?v=4","01M74KK34WVHA0P5ZYSJRDDFMG","Samuel Chien","01M74KK35FQN1N9VZ9EPTH3P2S",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fimplementing-api-security-posture-management\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fimplementing-api-security-posture-management\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: implementing-api-security-posture-management\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: [api-security, aspm, api-posture-management, api-discovery, risk-scoring, api-governance, continuous-monitoring, api-inventory]\nversion: \"1.0\"\nauthor: mahipal\nlicense: Apache-2.0\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":25,"author":34,"domain":35,"license":15,"version":36,"subdomain":26,"description":7},[26,27,28,29,30,31,32,33],"api-security","aspm","api-posture-management","api-discovery","risk-scoring","api-governance","continuous-monitoring","api-inventory","mahipal","cybersecurity","1.0","main","c2b1fdccc779e99ac814e55fb69ca8d71215dd0f","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection","https:\u002F\u002Fgithub.com\u002FSamuelChien","http:\u002F\u002Fsamuelchien.com\u002F","2026-05-26 08:27:14",{"source":8,"skillName":5,"commands":44,"prompt":54,"zipAvailable":55},[45,48,51],{"tool":46,"command":47},"npx","npx skills add SamuelChien\u002Fmega-skills-collection --skill implementing-api-security-posture-management",{"tool":49,"command":50},"bunx","bunx skills add SamuelChien\u002Fmega-skills-collection --skill implementing-api-security-posture-management",{"tool":52,"command":53},"pnpm","pnpm dlx skills add SamuelChien\u002Fmega-skills-collection --skill implementing-api-security-posture-management","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fimplementing-api-security-posture-management\u002FSKILL.md",true,[57,61,67],{"path":58,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":60,"sourceHtmlUrl":16},"LICENSE","许可证",11255,{"path":62,"resourceType":63,"resourceTypeDesc":64,"sizeBytes":65,"sourceHtmlUrl":66},"references\u002Fapi-reference.md","REFERENCE","参考文档",1466,"https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fimplementing-api-security-posture-management\u002Freferences\u002Fapi-reference.md",{"path":68,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":71,"sourceHtmlUrl":72},"scripts\u002Fagent.py","SCRIPT","脚本",6253,"https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fimplementing-api-security-posture-management\u002Fscripts\u002Fagent.py",[74,82,89,96,103,110],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":78,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":20},"01M76R4WZQZAXGGXMQCA0FZ716","zustand-store-ts","Create Zustand stores with TypeScript, subscribeWithSelector middleware, and proper state\u002Faction separation. Use when building React state management, creating global stores, or implementing reactive state patterns with Zustand.","MIT","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fzustand-store-ts\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":78,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":20},"01M76R4T9KENDH7FENGZQHBW4G","zustand-store-creator","Zustand Store Creator - Auto-activating skill for Frontend Development.\nTriggers on: zustand store creator, zustand store creator\nPart of the Frontend Development skill category.","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fzustand-store-creator\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":78,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":20},"01M76R3YWN84B7SANJ52X799ZE","zero-trust-config-helper","Zero Trust Config Helper - Auto-activating skill for Security Advanced.\nTriggers on: zero trust config helper, zero trust config helper\nPart of the Security Advanced skill category.","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fzero-trust-config-helper\u002FSKILL.md",[],[],{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":78,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":20},"01M76R3HNSV2AEYSKHM915GJ58","zapier-integration-helper","Zapier Integration Helper - Auto-activating skill for Business Automation.\nTriggers on: zapier integration helper, zapier integration helper\nPart of the Business Automation skill category.","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fzapier-integration-helper\u002FSKILL.md",[],[],{"skillNo":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":20},"01M76R3DJSKAT4FA7DV4BF3GCE","zai-cli","Execute z.AI CLI providing vision, search, reader, and GitHub exploration via CLI and MCP.\nUse when user needs image\u002Fvideo analysis, OCR, UI-to-code conversion, error diagnosis,\nreal-time web search, web page to markdown extraction, or GitHub code exploration.\nTrigger with phrases like \"analyze this image\", \"search the web for\", \"read this page\",\n\"explore this repo\", or \"use zai\". Requires Z_AI_API_KEY.","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fzai-cli\u002FSKILL.md",[],[],{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":78,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":20},"01M76R2KAM699XE9AJVAWE4H2E","yt-research","Research competitor YouTube channels, niches, and trending topics for your content strategy.\nUse this skill whenever the user says \"research channels\", \"analyze competitors\", \"find trending topics\",\n\"niche analysis\", \"competitive research\", \"what are other creators doing\", \"scrape YouTube channels\",\nor wants to understand the competitive landscape for a specific tool or topic area. Use when working with yt research. Trigger with 'yt', 'research'.","https:\u002F\u002Fgithub.com\u002FSamuelChien\u002Fmega-skills-collection\u002Fblob\u002Fmain\u002Fyt-research\u002FSKILL.md",[],[]]