[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M71GRC7DH7FA0W845G7BYPGW":3,"skill-same:01M71GRC7DH7FA0W845G7BYPGW":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":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":72,"commitSha":73,"skillDirectory":74,"forksCount":14,"repositoryHtmlUrl":75,"repositoryHomepageUrl":6,"ownerHtmlUrl":76,"ownerBlogUrl":6,"ownerDescription":77,"updatedAt":78,"install":79,"resources":92},"01M71GRC7DH7FA0W845G7BYPGW","api-schema-exploit",null,"Implement API schema validation using OpenAPI specifications and JSON Schema to enforce input\u002Foutput contracts and prevent injection, data exposure, and mass assignment attacks.","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\u002Fschema\u002Fexploit\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"api schema exploit","exploit","schema","api","json schema","sonnet","contracts","prevention","security","injection","input","data","data-leakage","read","de","exposure","Bash","cybersecurity","api-security","cm","2026-11-10 10:12:30",false,"---\nname: api-schema-exploit\ndescription: Implement API schema validation using OpenAPI specifications and JSON Schema to enforce input\u002Foutput contracts and prevent injection, data exposure, and mass assignment attacks.\ndomain: cybersecurity\nsubdomain: api-security\ntags:\n- api-security\n- schema-validation\n- openapi\n- json-schema\n- input-validation\n- data-leakage-prevention\n- mass-assignment\n- api-gateway\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- T1189\n- T1190\ncwe:\n- CWE-20\n- CWE-611\n- CWE-79\n- CWE-89\n- CWE-915\ncapec: []\n---\n\n# Implementing API Schema Validation Security\n\n## Overview\n\nAPI schema validation enforces that all data exchanged through APIs conforms to a predefined structure defined in OpenAPI Specification (OAS) or JSON Schema documents. This prevents injection attacks (SQLi, XSS, XXE), blocks mass assignment by rejecting unknown properties, prevents data leakage by validating response schemas, and ensures type safety across all API interactions. Schema validation operates at both the API gateway level (runtime enforcement) and during development (shift-left security).\n\n\n## When to Use\n\n- When deploying or configuring implementing api schema validation security 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- OpenAPI Specification v3.0 or v3.1 for all API endpoints\n- API gateway with schema validation support (Cloudflare API Shield, Kong, AWS API Gateway)\n- JSON Schema draft-07 or later understanding\n- Development environment with OpenAPI validation libraries\n- CI\u002FCD pipeline for automated schema compliance testing\n\n## Core Implementation\n\n### OpenAPI Schema with Security Constraints\n\n```yaml\nopenapi: 3.1.0\ninfo:\n  title: Secure E-Commerce API\n  version: 2.0.0\nservers:\n  - url: https:\u002F\u002Fapi.example.com\u002Fv2\n    description: Production (HTTPS enforced)\nsecurity:\n  - OAuth2:\n      - read:products\n      - write:orders\n\npaths:\n  \u002Fproducts:\n    post:\n      operationId: createProduct\n      security:\n        - OAuth2: [write:products]\n      requestBody:\n        required: true\n        content:\n          application\u002Fjson:\n            schema:\n              $ref: '#\u002Fcomponents\u002Fschemas\u002FProductCreate'\n      responses:\n        '201':\n          description: Product created\n          content:\n            application\u002Fjson:\n              schema:\n                $ref: '#\u002Fcomponents\u002Fschemas\u002FProduct'\n        '400':\n          $ref: '#\u002Fcomponents\u002Fresponses\u002FValidationError'\n        '401':\n          $ref: '#\u002Fcomponents\u002Fresponses\u002FUnauthorized'\n\n  \u002Fproducts\u002F{productId}:\n    get:\n      operationId: getProduct\n      parameters:\n        - name: productId\n          in: path\n          required: true\n          schema:\n            type: string\n            format: uuid\n            pattern: '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'\n      responses:\n        '200':\n          content:\n            application\u002Fjson:\n              schema:\n                $ref: '#\u002Fcomponents\u002Fschemas\u002FProduct'\n\ncomponents:\n  schemas:\n    ProductCreate:\n      type: object\n      required: [name, price, category]\n      properties:\n        name:\n          type: string\n          minLength: 1\n          maxLength: 200\n          pattern: '^[a-zA-Z0-9\\s\\-\\.]+$'  # No special chars for injection prevention\n        description:\n          type: string\n          maxLength: 2000\n          # Sanitize HTML entities\n        price:\n          type: number\n          format: float\n          minimum: 0.01\n          maximum: 999999.99\n          exclusiveMinimum: 0\n        category:\n          type: string\n          enum: [electronics, clothing, food, furniture, other]\n        tags:\n          type: array\n          items:\n            type: string\n            maxLength: 50\n            pattern: '^[a-zA-Z0-9\\-]+$'\n          maxItems: 10\n          uniqueItems: true\n      additionalProperties: false  # CRITICAL: Prevents mass assignment\n\n    Product:\n      type: object\n      required: [id, name, price]\n      properties:\n        id:\n          type: string\n          format: uuid\n          readOnly: true\n        name:\n          type: string\n        price:\n          type: number\n        category:\n          type: string\n        tags:\n          type: array\n          items:\n            type: string\n        createdAt:\n          type: string\n          format: date-time\n          readOnly: true\n      additionalProperties: false  # Prevents data leakage of internal fields\n\n    ValidationErrorResponse:\n      type: object\n      required: [code, message]\n      properties:\n        code:\n          type: string\n          enum: [VALIDATION_ERROR]\n        message:\n          type: string\n          maxLength: 500\n        details:\n          type: array\n          items:\n            type: object\n            properties:\n              field:\n                type: string\n              error:\n                type: string\n            additionalProperties: false\n          maxItems: 50\n      additionalProperties: false\n\n  responses:\n    ValidationError:\n      description: Request validation failed\n      content:\n        application\u002Fjson:\n          schema:\n            $ref: '#\u002Fcomponents\u002Fschemas\u002FValidationErrorResponse'\n    Unauthorized:\n      description: Authentication required\n\n  securitySchemes:\n    OAuth2:\n      type: oauth2\n      flows:\n        authorizationCode:\n          authorizationUrl: https:\u002F\u002Fauth.example.com\u002Fauthorize\n          tokenUrl: https:\u002F\u002Fauth.example.com\u002Ftoken\n          scopes:\n            read:products: Read product data\n            write:products: Create and update products\n            write:orders: Create orders\n```\n\n### Server-Side Schema Validation (Python\u002FFastAPI)\n\n```python\n\"\"\"API Schema Validation Middleware for FastAPI\n\nEnforces strict schema validation on all request and response payloads\nto prevent injection, mass assignment, and data leakage attacks.\n\"\"\"\n\nfrom fastapi import FastAPI, Request, Response, HTTPException\nfrom fastapi.middleware import Middleware\nfrom pydantic import BaseModel, Field, field_validator, ConfigDict\nfrom typing import List, Optional\nimport re\nimport json\nfrom starlette.middleware.base import BaseHTTPMiddleware\n\napp = FastAPI()\n\n\n# Strict Pydantic models with security constraints\nclass ProductCreate(BaseModel):\n    model_config = ConfigDict(extra='forbid')  # Reject unknown fields (mass assignment)\n\n    name: str = Field(min_length=1, max_length=200, pattern=r'^[a-zA-Z0-9\\s\\-\\.]+$')\n    description: Optional[str] = Field(default=None, max_length=2000)\n    price: float = Field(gt=0, le=999999.99)\n    category: str = Field(pattern=r'^(electronics|clothing|food|furniture|other)$')\n    tags: Optional[List[str]] = Field(default=None, max_length=10)\n\n    @field_validator('name')\n    @classmethod\n    def sanitize_name(cls, v):\n        # Prevent XSS via HTML entities\n        dangerous_patterns = ['\u003Cscript', 'javascript:', 'onerror=', 'onload=']\n        lower_v = v.lower()\n        for pattern in dangerous_patterns:\n            if pattern in lower_v:\n                raise ValueError(f'Invalid characters in name')\n        return v\n\n    @field_validator('description')\n    @classmethod\n    def sanitize_description(cls, v):\n        if v is None:\n            return v\n        # Strip potential SQL injection patterns\n        sql_patterns = [\n            r\"('|--|;|\u002F\\*|\\*\u002F|xp_|exec\\s|union\\s+select|drop\\s+table)\",\n        ]\n        for pattern in sql_patterns:\n            if re.search(pattern, v, re.IGNORECASE):\n                raise ValueError('Invalid content in description')\n        return v\n\n    @field_validator('tags')\n    @classmethod\n    def validate_tags(cls, v):\n        if v is None:\n            return v\n        if len(v) > 10:\n            raise ValueError('Maximum 10 tags allowed')\n        for tag in v:\n            if not re.match(r'^[a-zA-Z0-9\\-]+$', tag) or len(tag) > 50:\n                raise ValueError(f'Invalid tag format: {tag}')\n        return v\n\n\nclass ProductResponse(BaseModel):\n    \"\"\"Response model that explicitly defines allowed output fields.\n    Prevents leakage of internal fields like internal_notes, cost_price, etc.\"\"\"\n    model_config = ConfigDict(extra='forbid')\n\n    id: str\n    name: str\n    price: float\n    category: str\n    tags: List[str] = []\n    created_at: str\n\n\nclass ResponseValidationMiddleware(BaseHTTPMiddleware):\n    \"\"\"Middleware to validate response payloads against schema.\n    Prevents accidental data leakage by checking response content.\"\"\"\n\n    SCHEMA_MAP = {\n        '\u002Fapi\u002Fv2\u002Fproducts': {\n            'POST': {'response_model': ProductResponse},\n            'GET': {'response_model': ProductResponse},\n        }\n    }\n\n    async def dispatch(self, request: Request, call_next):\n        response = await call_next(request)\n\n        # Only validate JSON responses\n        content_type = response.headers.get('content-type', '')\n        if 'application\u002Fjson' not in content_type:\n            return response\n\n        # Check if endpoint has a registered response schema\n        path = request.url.path\n        method = request.method\n\n        route_config = self.SCHEMA_MAP.get(path, {}).get(method)\n        if not route_config:\n            return response\n\n        # Read and validate response body\n        body = b\"\"\n        async for chunk in response.body_iterator:\n            body += chunk\n\n        try:\n            data = json.loads(body)\n            model = route_config['response_model']\n            if isinstance(data, list):\n                for item in data:\n                    model.model_validate(item)\n            else:\n                model.model_validate(data)\n        except Exception as e:\n            # Log the validation failure for security monitoring\n            print(f\"SECURITY: Response schema violation on {method} {path}: {e}\")\n            # Return a safe error instead of potentially leaked data\n            return Response(\n                content=json.dumps({\"error\": \"Internal server error\"}),\n                status_code=500,\n                media_type=\"application\u002Fjson\"\n            )\n\n        return Response(\n            content=body,\n            status_code=response.status_code,\n            headers=dict(response.headers),\n            media_type=response.media_type\n        )\n\n\napp.add_middleware(ResponseValidationMiddleware)\n\n\n@app.post(\"\u002Fapi\u002Fv2\u002Fproducts\", response_model=ProductResponse, status_code=201)\nasync def create_product(product: ProductCreate):\n    # ProductCreate model with extra='forbid' automatically rejects\n    # any unknown fields, preventing mass assignment attacks\n    # (e.g., attacker trying to set is_admin=true or price=0)\n    pass\n```\n\n### Cloudflare API Shield Schema Validation\n\n```bash\n# Upload OpenAPI schema to Cloudflare API Shield\ncurl -X POST \"https:\u002F\u002Fapi.cloudflare.com\u002Fclient\u002Fv4\u002Fzones\u002F{zone_id}\u002Fapi_gateway\u002Fuser_schemas\" \\\n  -H \"Authorization: Bearer ${CF_API_TOKEN}\" \\\n  -H \"Content-Type: multipart\u002Fform-data\" \\\n  -F \"file=@openapi.yaml\" \\\n  -F \"kind=openapi_v3\"\n\n# Enable schema validation with blocking mode\ncurl -X PATCH \"https:\u002F\u002Fapi.cloudflare.com\u002Fclient\u002Fv4\u002Fzones\u002F{zone_id}\u002Fapi_gateway\u002Fsettings\u002Fschema_validation\" \\\n  -H \"Authorization: Bearer ${CF_API_TOKEN}\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"validation_default_mitigation_action\": \"block\",\n    \"validation_override_mitigation_action\": null\n  }'\n```\n\n### CI\u002FCD Schema Compliance Testing\n\n```yaml\n# GitHub Actions workflow for schema validation in CI\nname: api-schema\non:\n  pull_request:\n    paths: ['api\u002F**', 'openapi\u002F**']\n\njobs:\n  schema-security:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n\n      - name: Validate OpenAPI Schema\n        run: |\n          npm install -g @stoplight\u002Fspectral-cli\n          spectral lint openapi.yaml --ruleset .spectral-security.yaml\n\n      - name: Check for Security Anti-Patterns\n        run: |\n          python3 scripts\u002Fschema_security_check.py openapi.yaml\n\n      - name: Run Contract Tests\n        run: |\n          npm install -g dredd\n          dredd openapi.yaml http:\u002F\u002Flocalhost:3000 --hookfiles=.\u002Ftest\u002Fhooks.js\n```\n\n## Security Anti-Patterns to Detect\n\n| Anti-Pattern | Risk | Fix |\n|---|---|---|\n| `additionalProperties: true` or missing | Mass assignment | Set `additionalProperties: false` |\n| No `maxLength` on strings | Buffer overflow, DoS | Add appropriate `maxLength` constraints |\n| No `pattern` on string fields | Injection attacks | Add regex patterns to restrict input |\n| No `enum` for fixed-value fields | Unexpected input processing | Use `enum` for fields with known values |\n| `format: password` without TLS | Credential exposure | Enforce HTTPS-only server URLs |\n| Missing error response schemas | Information leakage | Define all 4xx\u002F5xx response schemas |\n| `readOnly` fields in request body | Data manipulation | Enforce `readOnly` server-side |\n\n## References\n\n- OpenAPI Specification v3.1: https:\u002F\u002Fspec.openapis.org\u002Foas\u002Fv3.1.0\n- Cloudflare API Shield Schema Validation: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fapi-shield\u002Fsecurity\u002Fschema-validation\u002F\n- Redocly API Security by Design: https:\u002F\u002Fredocly.com\u002Flearn\u002Fsecurity\n- Impart Security API Validation: https:\u002F\u002Fwww.impart.ai\u002Fblog\u002Fdetect-and-fix-api-vulnerabilities-using-validation-secure-principles-and-real-time-response\n- OWASP API Security Top 10 2023: https:\u002F\u002Fowasp.org\u002FAPI-Security\u002Feditions\u002F2023\u002Fen\u002F0x00-header\u002F\n","# Implementing API Schema Validation Security\n\n## Overview\n\nAPI schema validation enforces that all data exchanged through APIs conforms to a predefined structure defined in OpenAPI Specification (OAS) or JSON Schema documents. This prevents injection attacks (SQLi, XSS, XXE), blocks mass assignment by rejecting unknown properties, prevents data leakage by validating response schemas, and ensures type safety across all API interactions. Schema validation operates at both the API gateway level (runtime enforcement) and during development (shift-left security).\n\n\n## When to Use\n\n- When deploying or configuring implementing api schema validation security 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- OpenAPI Specification v3.0 or v3.1 for all API endpoints\n- API gateway with schema validation support (Cloudflare API Shield, Kong, AWS API Gateway)\n- JSON Schema draft-07 or later understanding\n- Development environment with OpenAPI validation libraries\n- CI\u002FCD pipeline for automated schema compliance testing\n\n## Core Implementation\n\n### OpenAPI Schema with Security Constraints\n\n```yaml\nopenapi: 3.1.0\ninfo:\n  title: Secure E-Commerce API\n  version: 2.0.0\nservers:\n  - url: https:\u002F\u002Fapi.example.com\u002Fv2\n    description: Production (HTTPS enforced)\nsecurity:\n  - OAuth2:\n      - read:products\n      - write:orders\n\npaths:\n  \u002Fproducts:\n    post:\n      operationId: createProduct\n      security:\n        - OAuth2: [write:products]\n      requestBody:\n        required: true\n        content:\n          application\u002Fjson:\n            schema:\n              $ref: '#\u002Fcomponents\u002Fschemas\u002FProductCreate'\n      responses:\n        '201':\n          description: Product created\n          content:\n            application\u002Fjson:\n              schema:\n                $ref: '#\u002Fcomponents\u002Fschemas\u002FProduct'\n        '400':\n          $ref: '#\u002Fcomponents\u002Fresponses\u002FValidationError'\n        '401':\n          $ref: '#\u002Fcomponents\u002Fresponses\u002FUnauthorized'\n\n  \u002Fproducts\u002F{productId}:\n    get:\n      operationId: getProduct\n      parameters:\n        - name: productId\n          in: path\n          required: true\n          schema:\n            type: string\n            format: uuid\n            pattern: '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'\n      responses:\n        '200':\n          content:\n            application\u002Fjson:\n              schema:\n                $ref: '#\u002Fcomponents\u002Fschemas\u002FProduct'\n\ncomponents:\n  schemas:\n    ProductCreate:\n      type: object\n      required: [name, price, category]\n      properties:\n        name:\n          type: string\n          minLength: 1\n          maxLength: 200\n          pattern: '^[a-zA-Z0-9\\s\\-\\.]+$'  # No special chars for injection prevention\n        description:\n          type: string\n          maxLength: 2000\n          # Sanitize HTML entities\n        price:\n          type: number\n          format: float\n          minimum: 0.01\n          maximum: 999999.99\n          exclusiveMinimum: 0\n        category:\n          type: string\n          enum: [electronics, clothing, food, furniture, other]\n        tags:\n          type: array\n          items:\n            type: string\n            maxLength: 50\n            pattern: '^[a-zA-Z0-9\\-]+$'\n          maxItems: 10\n          uniqueItems: true\n      additionalProperties: false  # CRITICAL: Prevents mass assignment\n\n    Product:\n      type: object\n      required: [id, name, price]\n      properties:\n        id:\n          type: string\n          format: uuid\n          readOnly: true\n        name:\n          type: string\n        price:\n          type: number\n        category:\n          type: string\n        tags:\n          type: array\n          items:\n            type: string\n        createdAt:\n          type: string\n          format: date-time\n          readOnly: true\n      additionalProperties: false  # Prevents data leakage of internal fields\n\n    ValidationErrorResponse:\n      type: object\n      required: [code, message]\n      properties:\n        code:\n          type: string\n          enum: [VALIDATION_ERROR]\n        message:\n          type: string\n          maxLength: 500\n        details:\n          type: array\n          items:\n            type: object\n            properties:\n              field:\n                type: string\n              error:\n                type: string\n            additionalProperties: false\n          maxItems: 50\n      additionalProperties: false\n\n  responses:\n    ValidationError:\n      description: Request validation failed\n      content:\n        application\u002Fjson:\n          schema:\n            $ref: '#\u002Fcomponents\u002Fschemas\u002FValidationErrorResponse'\n    Unauthorized:\n      description: Authentication required\n\n  securitySchemes:\n    OAuth2:\n      type: oauth2\n      flows:\n        authorizationCode:\n          authorizationUrl: https:\u002F\u002Fauth.example.com\u002Fauthorize\n          tokenUrl: https:\u002F\u002Fauth.example.com\u002Ftoken\n          scopes:\n            read:products: Read product data\n            write:products: Create and update products\n            write:orders: Create orders\n```\n\n### Server-Side Schema Validation (Python\u002FFastAPI)\n\n```python\n\"\"\"API Schema Validation Middleware for FastAPI\n\nEnforces strict schema validation on all request and response payloads\nto prevent injection, mass assignment, and data leakage attacks.\n\"\"\"\n\nfrom fastapi import FastAPI, Request, Response, HTTPException\nfrom fastapi.middleware import Middleware\nfrom pydantic import BaseModel, Field, field_validator, ConfigDict\nfrom typing import List, Optional\nimport re\nimport json\nfrom starlette.middleware.base import BaseHTTPMiddleware\n\napp = FastAPI()\n\n\n# Strict Pydantic models with security constraints\nclass ProductCreate(BaseModel):\n    model_config = ConfigDict(extra='forbid')  # Reject unknown fields (mass assignment)\n\n    name: str = Field(min_length=1, max_length=200, pattern=r'^[a-zA-Z0-9\\s\\-\\.]+$')\n    description: Optional[str] = Field(default=None, max_length=2000)\n    price: float = Field(gt=0, le=999999.99)\n    category: str = Field(pattern=r'^(electronics|clothing|food|furniture|other)$')\n    tags: Optional[List[str]] = Field(default=None, max_length=10)\n\n    @field_validator('name')\n    @classmethod\n    def sanitize_name(cls, v):\n        # Prevent XSS via HTML entities\n        dangerous_patterns = ['\u003Cscript', 'javascript:', 'onerror=', 'onload=']\n        lower_v = v.lower()\n        for pattern in dangerous_patterns:\n            if pattern in lower_v:\n                raise ValueError(f'Invalid characters in name')\n        return v\n\n    @field_validator('description')\n    @classmethod\n    def sanitize_description(cls, v):\n        if v is None:\n            return v\n        # Strip potential SQL injection patterns\n        sql_patterns = [\n            r\"('|--|;|\u002F\\*|\\*\u002F|xp_|exec\\s|union\\s+select|drop\\s+table)\",\n        ]\n        for pattern in sql_patterns:\n            if re.search(pattern, v, re.IGNORECASE):\n                raise ValueError('Invalid content in description')\n        return v\n\n    @field_validator('tags')\n    @classmethod\n    def validate_tags(cls, v):\n        if v is None:\n            return v\n        if len(v) > 10:\n            raise ValueError('Maximum 10 tags allowed')\n        for tag in v:\n            if not re.match(r'^[a-zA-Z0-9\\-]+$', tag) or len(tag) > 50:\n                raise ValueError(f'Invalid tag format: {tag}')\n        return v\n\n\nclass ProductResponse(BaseModel):\n    \"\"\"Response model that explicitly defines allowed output fields.\n    Prevents leakage of internal fields like internal_notes, cost_price, etc.\"\"\"\n    model_config = ConfigDict(extra='forbid')\n\n    id: str\n    name: str\n    price: float\n    category: str\n    tags: List[str] = []\n    created_at: str\n\n\nclass ResponseValidationMiddleware(BaseHTTPMiddleware):\n    \"\"\"Middleware to validate response payloads against schema.\n    Prevents accidental data leakage by checking response content.\"\"\"\n\n    SCHEMA_MAP = {\n        '\u002Fapi\u002Fv2\u002Fproducts': {\n            'POST': {'response_model': ProductResponse},\n            'GET': {'response_model': ProductResponse},\n        }\n    }\n\n    async def dispatch(self, request: Request, call_next):\n        response = await call_next(request)\n\n        # Only validate JSON responses\n        content_type = response.headers.get('content-type', '')\n        if 'application\u002Fjson' not in content_type:\n            return response\n\n        # Check if endpoint has a registered response schema\n        path = request.url.path\n        method = request.method\n\n        route_config = self.SCHEMA_MAP.get(path, {}).get(method)\n        if not route_config:\n            return response\n\n        # Read and validate response body\n        body = b\"\"\n        async for chunk in response.body_iterator:\n            body += chunk\n\n        try:\n            data = json.loads(body)\n            model = route_config['response_model']\n            if isinstance(data, list):\n                for item in data:\n                    model.model_validate(item)\n            else:\n                model.model_validate(data)\n        except Exception as e:\n            # Log the validation failure for security monitoring\n            print(f\"SECURITY: Response schema violation on {method} {path}: {e}\")\n            # Return a safe error instead of potentially leaked data\n            return Response(\n                content=json.dumps({\"error\": \"Internal server error\"}),\n                status_code=500,\n                media_type=\"application\u002Fjson\"\n            )\n\n        return Response(\n            content=body,\n            status_code=response.status_code,\n            headers=dict(response.headers),\n            media_type=response.media_type\n        )\n\n\napp.add_middleware(ResponseValidationMiddleware)\n\n\n@app.post(\"\u002Fapi\u002Fv2\u002Fproducts\", response_model=ProductResponse, status_code=201)\nasync def create_product(product: ProductCreate):\n    # ProductCreate model with extra='forbid' automatically rejects\n    # any unknown fields, preventing mass assignment attacks\n    # (e.g., attacker trying to set is_admin=true or price=0)\n    pass\n```\n\n### Cloudflare API Shield Schema Validation\n\n```bash\n# Upload OpenAPI schema to Cloudflare API Shield\ncurl -X POST \"https:\u002F\u002Fapi.cloudflare.com\u002Fclient\u002Fv4\u002Fzones\u002F{zone_id}\u002Fapi_gateway\u002Fuser_schemas\" \\\n  -H \"Authorization: Bearer ${CF_API_TOKEN}\" \\\n  -H \"Content-Type: multipart\u002Fform-data\" \\\n  -F \"file=@openapi.yaml\" \\\n  -F \"kind=openapi_v3\"\n\n# Enable schema validation with blocking mode\ncurl -X PATCH \"https:\u002F\u002Fapi.cloudflare.com\u002Fclient\u002Fv4\u002Fzones\u002F{zone_id}\u002Fapi_gateway\u002Fsettings\u002Fschema_validation\" \\\n  -H \"Authorization: Bearer ${CF_API_TOKEN}\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"validation_default_mitigation_action\": \"block\",\n    \"validation_override_mitigation_action\": null\n  }'\n```\n\n### CI\u002FCD Schema Compliance Testing\n\n```yaml\n# GitHub Actions workflow for schema validation in CI\nname: api-schema\non:\n  pull_request:\n    paths: ['api\u002F**', 'openapi\u002F**']\n\njobs:\n  schema-security:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n\n      - name: Validate OpenAPI Schema\n        run: |\n          npm install -g @stoplight\u002Fspectral-cli\n          spectral lint openapi.yaml --ruleset .spectral-security.yaml\n\n      - name: Check for Security Anti-Patterns\n        run: |\n          python3 scripts\u002Fschema_security_check.py openapi.yaml\n\n      - name: Run Contract Tests\n        run: |\n          npm install -g dredd\n          dredd openapi.yaml http:\u002F\u002Flocalhost:3000 --hookfiles=.\u002Ftest\u002Fhooks.js\n```\n\n## Security Anti-Patterns to Detect\n\n| Anti-Pattern | Risk | Fix |\n|---|---|---|\n| `additionalProperties: true` or missing | Mass assignment | Set `additionalProperties: false` |\n| No `maxLength` on strings | Buffer overflow, DoS | Add appropriate `maxLength` constraints |\n| No `pattern` on string fields | Injection attacks | Add regex patterns to restrict input |\n| No `enum` for fixed-value fields | Unexpected input processing | Use `enum` for fields with known values |\n| `format: password` without TLS | Credential exposure | Enforce HTTPS-only server URLs |\n| Missing error response schemas | Information leakage | Define all 4xx\u002F5xx response schemas |\n| `readOnly` fields in request body | Data manipulation | Enforce `readOnly` server-side |\n\n## References\n\n- OpenAPI Specification v3.1: https:\u002F\u002Fspec.openapis.org\u002Foas\u002Fv3.1.0\n- Cloudflare API Shield Schema Validation: https:\u002F\u002Fdevelopers.cloudflare.com\u002Fapi-shield\u002Fsecurity\u002Fschema-validation\u002F\n- Redocly API Security by Design: https:\u002F\u002Fredocly.com\u002Flearn\u002Fsecurity\n- Impart Security API Validation: https:\u002F\u002Fwww.impart.ai\u002Fblog\u002Fdetect-and-fix-api-vulnerabilities-using-validation-secure-principles-and-real-time-response\n- OWASP API Security Top 10 2023: https:\u002F\u002Fowasp.org\u002FAPI-Security\u002Feditions\u002F2023\u002Fen\u002F0x00-header\u002F\n",{"cwe":44,"name":5,"tags":50,"capec":58,"model":24,"tools":59,"domain":36,"maxTurns":63,"nist_csf":64,"subdomain":37,"description":7,"mitre_attack":69},[45,46,47,48,49],"CWE-20","CWE-611","CWE-79","CWE-89","CWE-915",[37,51,52,53,54,55,56,57],"schema-validation","openapi","json-schema","input-validation","data-leakage-prevention","mass-assignment","api-gateway",[],[60,35,61,62],"Read","Glob","Grep",20,[65,66,67,68],"PR.PS-01","ID.RA-01","PR.DS-10","DE.CM-01",[70,71],"T1189","T1190","main","a91f1293287ffa9f4f1b8f486cd6e835a1568c84","skills\u002Fweb-application\u002Fapi\u002Fschema\u002Fexploit","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-schema-exploit",{"tool":85,"command":86},"bunx","bunx skills add DCx7C5\u002Fai-marketplace --skill api-schema-exploit",{"tool":88,"command":89},"pnpm","pnpm dlx skills add DCx7C5\u002Fai-marketplace --skill api-schema-exploit","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fweb-application\u002Fapi\u002Fschema\u002Fexploit\u002FSKILL.md",true,[93],{"path":94,"resourceType":95,"resourceTypeDesc":96,"sizeBytes":97,"sourceHtmlUrl":98},"index.json","REFERENCE","参考文档",662,"https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fweb-application\u002Fapi\u002Fschema\u002Fexploit\u002Findex.json",[100,110,133,153,174,196],{"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":104,"licenseFileUrl":105,"sourceHtmlUrl":106,"categories":107,"keywords":108,"publishedAt":109},"01M73MDK3NT5XHNYTQ5P5172V9","devel-jb-algorithmic-art","- Embed algorithms inline in the HTML artifact (don't create separate .","Apache-2.0","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fdevel-jb-algorithmic-art\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002FDCx7C5\u002Fai-marketplace\u002Fblob\u002Fmain\u002Fskills\u002Fdevel-jb-algorithmic-art\u002FSKILL.md",[],[],"2026-11-11 15:11:14",{"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":15,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":39},"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",[],[117,118,119,120,121,122,123,36,124,125,126,127,128,129,130,131,132,38,33],"services","detect","services wmi persistence detect","wmi","persistence","process-forensics","process","forensics","t1546.003","event-subscription","subscription","repository","commandline-consumer","subscriptions","event","activescript",{"skillNo":134,"name":135,"nameZh":6,"description":136,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":137,"categories":138,"keywords":139,"publishedAt":39},"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",[],[140,120,141,117,20,142,35,143,144,36,145,146,147,148,149,32,150,151,33,152],"exec","services wmi exec exploit","across","analysis","team","traffic","remote","crackmapexec","Impacket","lateral-movement","lateral movement","command","native",{"skillNo":154,"name":155,"nameZh":6,"description":156,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":157,"categories":158,"keywords":159,"publishedAt":39},"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",[],[160,161,162,163,164,24,165,166,167,168,32,33,169,170,143,171,35,36,172,173],"extract","registry artifact extract","registry","artifact","digital-forensics","regripper","windows-registry","evidence-collection","software","uncover","analyze","collection","artifact-analysis","activity",{"skillNo":175,"name":176,"nameZh":6,"description":177,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":178,"categories":179,"keywords":180,"publishedAt":39},"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",[],[181,182,183,118,36,184,38,185,186,187,122,33,188,189,190,191,192,193,194,195],"processes","token","processes token impersonate detect","techniques","escalation","windows","attacks","via","impersonation","potato","exploitation","printspoofer","token-impersonation","seimpersonate","privilege-escalation",{"skillNo":197,"name":198,"nameZh":6,"description":199,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":200,"categories":201,"keywords":202,"publishedAt":39},"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",[],[203,181,28,118,204,205,123,33,188,206,207,22,143,122,36,184,208,38,209,186],"thread","processes thread injection detect","thread-injection","nt-api","apc-injection","process-injection","memory"]