[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6AEYZ556T5TTPQSHAX93YWN":3,"skill-same:01M6AEYZ556T5TTPQSHAX93YWN":112},{"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":71,"commitSha":72,"skillDirectory":73,"forksCount":74,"repositoryHtmlUrl":75,"repositoryHomepageUrl":76,"ownerHtmlUrl":77,"ownerBlogUrl":78,"ownerDescription":79,"updatedAt":80,"install":81,"resources":94},"01M6AEYZ556T5TTPQSHAX93YWN","implementing-api-schema-validation-security",null,"Implements API schema validation using OpenAPI Specification and JSON Schema documents, enforced both at the API gateway (runtime) and during development (shift-left), to lock down request\u002Fresponse contracts and reject unknown properties. Use when preventing injection attacks (SQLi, XSS, XXE), blocking mass assignment, or stopping data leakage through unvalidated API responses.","mukul975\u002FAnthropic-Cybersecurity-Skills","mukul975","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F42860185?v=4","01M6ADEQR8T5M4EEG6C67BQCWF","Mahipal","01M6ADJPMYWG1E5GM1FWBE3128",36146,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-schema-validation-security\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],"implementing api schema validation security","validation","security","data","json-schema","openapi","schema-validation","api-gateway","prevention","xss","sqli","injection","api-security","gateway","api gateway","development","json schema","pr","documents","cybersecurity","2026-11-10 10:12:30",false,"---\nname: implementing-api-schema-validation-security\ndescription: Implements API schema validation using OpenAPI Specification and JSON\n  Schema documents, enforced both at the API gateway (runtime) and during development\n  (shift-left), to lock down request\u002Fresponse contracts and reject unknown properties.\n  Use when preventing injection attacks (SQLi, XSS, XXE), blocking mass assignment,\n  or stopping data leakage through unvalidated API responses.\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\nversion: '1.0'\nauthor: mahipal\nlicense: Apache-2.0\nnist_csf:\n- PR.PS-01\n- ID.RA-01\n- PR.DS-10\n- DE.CM-01\nmitre_attack:\n- T1190\n- T1059.007\n- T1552.001\n- T1055\n- T1059\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 Security Check\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 Security Check\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",{"name":5,"tags":54,"author":58,"domain":48,"license":15,"version":59,"nist_csf":60,"subdomain":41,"description":7,"mitre_attack":65},[41,35,34,33,55,56,57,36],"input-validation","data-leakage-prevention","mass-assignment","mahipal","1.0",[61,62,63,64],"PR.PS-01","ID.RA-01","PR.DS-10","DE.CM-01",[66,67,68,69,70],"T1190","T1059.007","T1552.001","T1055","T1059","main","54a798831d2266a3ca61ce68a7acb80b81160d57","skills\u002Fimplementing-api-schema-validation-security",4425,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills","https:\u002F\u002Fmahipal.engineer\u002FAnthropic-Cybersecurity-Skills\u002F","https:\u002F\u002Fgithub.com\u002Fmukul975","Mahipal.engineer","🔐 Cybersecurity | 💻 Dev | 📷 Street Photographer\r\n🎓 MSc | 📚 Research & AI Security","2026-08-31 12:32:44",{"source":8,"skillName":5,"commands":82,"prompt":92,"zipAvailable":93},[83,86,89],{"tool":84,"command":85},"npx","npx skills add mukul975\u002FAnthropic-Cybersecurity-Skills --skill implementing-api-schema-validation-security",{"tool":87,"command":88},"bunx","bunx skills add mukul975\u002FAnthropic-Cybersecurity-Skills --skill implementing-api-schema-validation-security",{"tool":90,"command":91},"pnpm","pnpm dlx skills add mukul975\u002FAnthropic-Cybersecurity-Skills --skill implementing-api-schema-validation-security","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-schema-validation-security\u002FSKILL.md",true,[95,100,106],{"path":96,"resourceType":96,"resourceTypeDesc":97,"sizeBytes":98,"sourceHtmlUrl":99},"LICENSE","许可证",11255,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-schema-validation-security\u002FLICENSE",{"path":101,"resourceType":102,"resourceTypeDesc":103,"sizeBytes":104,"sourceHtmlUrl":105},"references\u002Fapi-reference.md","REFERENCE","参考文档",1530,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-schema-validation-security\u002Freferences\u002Fapi-reference.md",{"path":107,"resourceType":108,"resourceTypeDesc":109,"sizeBytes":110,"sourceHtmlUrl":111},"scripts\u002Fagent.py","SCRIPT","脚本",7101,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-schema-validation-security\u002Fscripts\u002Fagent.py",[113,140,164,191,216,243],{"skillNo":114,"name":115,"nameZh":6,"description":116,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":117,"categories":118,"keywords":122,"publishedAt":49},"01M6AGDM3HJXTKXX15ZZ0ZVCJ3","verifying-build-provenance-with-slsa-sigstore","Verifies artifact signatures and SLSA provenance using Sigstore's cosign (verify, verify-attestation, verify-blob-attestation) and slsa-verifier (verify-artifact), enforcing keyless OIDC builder identity and source repo against SLSA Build levels. Use in CI\u002FCD before deploying artifacts, when consuming third-party attestations, establishing a SLSA Build L3 pipeline, or confirming provenance during incident response or admission control.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fverifying-build-provenance-with-slsa-sigstore\u002FSKILL.md",[119],{"categoryNo":120,"categoryName":121,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",[123,124,125,126,31,48,127,128,46,129,130,131,132,133,134,135,136,137,138,139],"sigstore","provenance","slsa","verifying build provenance with slsa sigstore","incident response","identity","code","artifacts","ci","supply-chain","pipeline","supply-chain-security","t1195","attestation","code-signing","cosign","keyless",{"skillNo":141,"name":142,"nameZh":6,"description":143,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":144,"categories":145,"keywords":147,"publishedAt":49},"01M6AGDGBPWYVZ2F11GFKJ4HZ9","validating-tpm-measured-boot-attestation","Verifies TPM 2.0 measured-boot integrity and remote attestation with tpm2-tools -- reading PCRs (tpm2_pcrread), replaying the boot event log, generating and checking signed quotes (tpm2_quote\u002Ftpm2_checkquote), and sealing secrets to a PCR policy. Use to confirm a system booted trusted firmware\u002Fkernel for Zero Trust device posture, detect boot-chain tampering via PCR drift, or build a golden-value baseline for fleet attestation.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fvalidating-tpm-measured-boot-attestation\u002FSKILL.md",[146],{"categoryNo":120,"categoryName":121,"taxonomyType":21,"taxonomyTypeDesc":22},[148,136,149,150,31,151,48,46,152,153,154,155,156,157,158,159,160,161,162,163],"boot","TPM","validating tpm measured boot attestation","policy","verification","ZeRO","firmware","Tools","measured-boot","PCR","integrity","secrets","remote-attestation","tpm2-tools","integrity-verification","trusted-computing",{"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":174,"publishedAt":49},"01M6AGDCW0Y4FXZ3362GT1941M","validating-backup-integrity-for-recovery","Validates backup integrity through cryptographic hash verification, automated restore testing, corruption detection, and recoverability checks to confirm backups are reliable for disaster recovery and ransomware response. Use before relying on backups for recovery, when building post-backup validation pipelines, auditing backup infrastructure for compliance, or checking immutable\u002Fair-gapped backups for silent corruption or tampering.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fvalidating-backup-integrity-for-recovery\u002FSKILL.md",[170,173],{"categoryNo":171,"categoryName":172,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000008","测试与质量",{"categoryNo":120,"categoryName":121,"taxonomyType":21,"taxonomyTypeDesc":22},[158,175,176,177,178,48,179,30,152,180,181,182,183,184,185,186,187,188,189,190],"backup","recovery","validating backup integrity for recovery","testing","infrastructure","compliance","hash-verification","incident-response","ransomware","cryptocurrency","detection","t1078","t1490","immutable","disaster-recovery","restore-testing",{"skillNo":192,"name":193,"nameZh":6,"description":194,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":195,"categories":196,"keywords":198,"publishedAt":49},"01M6AGD9GBG2KZ336AE763J3WH","triaging-windows-with-kape","Runs KAPE (Kroll Artifact Parser and Extractor) to collect targeted forensic artifacts (registry hives, $MFT, event logs, prefetch, browser data) via Targets and parse them with Modules wrapping Eric Zimmerman's EZ Tools (PECmd, MFTECmd, RECmd). Use during early incident containment\u002Ftriage when full disk imaging is impractical but a defensible, parseable Windows artifact set is needed quickly, including at-scale remote collection.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Ftriaging-windows-with-kape\u002FSKILL.md",[197],{"categoryNo":120,"categoryName":121,"taxonomyType":21,"taxonomyTypeDesc":22},[199,200,201,48,202,203,204,205,206,207,208,32,209,210,211,212,155,213,214,215],"windows","kape","triaging windows with kape","registry","browser","logs","windows-forensics","dfir","mft","mftecmd","prefetch","eric-zimmerman","digital-forensics","SET","collection","pecmd","artifact-collection",{"skillNo":217,"name":218,"nameZh":6,"description":219,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":220,"categories":221,"keywords":223,"publishedAt":49},"01M6AGD5PW5J4EVZM958WD74ZQ","triaging-vulnerabilities-with-ssvc-framework","Triages and prioritizes vulnerabilities with CISA's Stakeholder-Specific Vulnerability Categorization (SSVC) decision tree, weighing exploitation status (via the CISA KEV catalog and FIRST EPSS API), technical impact, automatability, and mission prevalence to output Track\u002FTrack*\u002FAttend\u002FAct decisions. Use when prioritizing vulnerability scan results (OpenVAS, Nessus, Qualys) for remediation planning beyond raw CVSS scores.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Ftriaging-vulnerabilities-with-ssvc-framework\u002FSKILL.md",[222],{"categoryNo":120,"categoryName":121,"taxonomyType":21,"taxonomyTypeDesc":22},[224,225,226,48,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242],"vulnerabilities","framework","triaging vulnerabilities with ssvc framework","status","planning","CISA","vulnerability-management","risk-management","nessus","qualys","openvas","cvss","remediation","risk","vulnerability","api","prioritization","ssvc","decision-tree",{"skillNo":244,"name":245,"nameZh":6,"description":246,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":247,"categories":248,"keywords":250,"publishedAt":49},"01M6AGD24TTQQM4CXG69E3B9TJ","triaging-security-incident","Performs initial triage of security incidents using the NIST SP 800-61r3 and SANS PICERL frameworks, classifying incident type, assigning priority by business impact, and routing to the appropriate response team. Use when a SIEM\u002FEDR alert needs human classification, concurrent alerts must be prioritized, or a user report or threat-intel IOC match requires initial incident categorization.","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Ftriaging-security-incident\u002FSKILL.md",[249],{"categoryNo":120,"categoryName":121,"taxonomyType":21,"taxonomyTypeDesc":22},[31,251,48,252,253,254,255,256,257,258,259,186,260,187,261,262,263,264,265,266],"triaging security incident","siem","file","ioc","soc","NIST-800-61","NIST","severity","edr","execution","analysis","classification","severity-classification","incident-triage","SANS-PICERL","SOC-operations"]