[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6AEYMR97GVGHXCBY5KNG494":3,"skill-same:01M6AEYMR97GVGHXCBY5KNG494":113},{"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":31,"publishedAt":52,"linkOnly":53,"markdownContent":54,"markdownBody":55,"frontMatter":56,"refName":72,"commitSha":73,"skillDirectory":74,"forksCount":75,"repositoryHtmlUrl":76,"repositoryHomepageUrl":77,"ownerHtmlUrl":78,"ownerBlogUrl":79,"ownerDescription":80,"updatedAt":81,"install":82,"resources":95},"01M6AEYMR97GVGHXCBY5KNG494","implementing-api-gateway-security-controls",null,"Configures API gateways such as Kong, AWS API Gateway, Azure APIM, or Apigee as a centralized security enforcement point, covering authentication enforcement, rate limiting and throttling, request validation, IP allowlisting, TLS termination, and threat protection. Use when securing API traffic at the gateway layer, setting up gateway-level authentication and quota management, or centralizing API protection before requests reach backend services.","mukul975\u002FAnthropic-Cybersecurity-Skills","mukul975","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F42860185?v=4","01M6ADEQR8T5M4EEG6C67BQCWF","Mahipal","01M6ADJPMYWG1E5GM1FWBE3128",35990,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-gateway-security-controls\u002FSKILL.md",[18,23,26],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000010","后端与接口","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",{"categoryNo":27,"categoryName":28,"taxonomyType":29,"taxonomyTypeDesc":30},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],"implementing api gateway security controls","api gateway","gateway","security","waf","api-gateway","t1059","t1078","tls","aws","kong","aws-api-gateway","api-security","services","gateways","validation","authentication","pr","azure","cybersecurity","2026-11-10 10:12:30",false,"---\nname: implementing-api-gateway-security-controls\ndescription: 'Configures API gateways such as Kong, AWS API Gateway, Azure APIM,\n  or Apigee as a centralized security enforcement point, covering authentication\n  enforcement, rate limiting and throttling, request validation, IP allowlisting,\n  TLS termination, and threat protection. Use when securing API traffic at the gateway\n  layer, setting up gateway-level authentication and quota management, or centralizing\n  API protection before requests reach backend services.'\ndomain: cybersecurity\nsubdomain: api-security\ntags:\n- api-security\n- api-gateway\n- kong\n- aws-api-gateway\n- rate-limiting\n- waf\nversion: 1.0.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- T1078.004\n- T1530\n---\n# Implementing API Gateway Security Controls\n\n## When to Use\n\n- Deploying a centralized authentication and authorization layer for microservice APIs\n- Implementing rate limiting, throttling, and quota management across all API endpoints\n- Configuring request\u002Fresponse validation against OpenAPI specifications at the gateway level\n- Setting up TLS termination, mutual TLS, and certificate management for API traffic\n- Integrating WAF rules with the API gateway to block injection, XSS, and known attack patterns\n\n**Do not use** as the sole security layer. API gateways provide defense in depth but backend services must also validate authorization and input.\n\n## Prerequisites\n\n- API gateway platform selected and deployed (Kong, AWS API Gateway, Azure APIM, or Apigee)\n- OpenAPI\u002FSwagger specifications for all backend APIs\n- TLS certificates for the gateway domain\n- Identity provider (IdP) configured for OAuth2\u002FOIDC (Okta, Auth0, Azure AD)\n- Monitoring and logging infrastructure (CloudWatch, Datadog, ELK)\n- Backend service endpoints registered and reachable from the gateway\n\n## Workflow\n\n### Step 1: Kong Gateway Security Configuration\n\n```yaml\n# kong.yml - Declarative Kong configuration with security plugins\n_format_version: \"3.0\"\n\nservices:\n  - name: user-service\n    url: http:\u002F\u002Fuser-service:8080\n    routes:\n      - name: user-api\n        paths:\n          - \u002Fapi\u002Fv1\u002Fusers\n        methods:\n          - GET\n          - POST\n          - PUT\n          - PATCH\n          - DELETE\n        strip_path: false\n\nplugins:\n  # 1. Authentication: JWT validation\n  - name: jwt\n    config:\n      uri_param_names:\n        - jwt\n      header_names:\n        - Authorization\n      claims_to_verify:\n        - exp\n      maximum_expiration: 3600  # Max 1 hour token TTL\n\n  # 2. Rate Limiting\n  - name: rate-limiting\n    config:\n      minute: 60\n      hour: 1000\n      policy: redis\n      redis_host: redis\n      redis_port: 6379\n      fault_tolerant: true\n      hide_client_headers: false\n      limit_by: credential  # Per-user, not per-IP\n\n  # 3. Request Size Limiting\n  - name: request-size-limiting\n    config:\n      allowed_payload_size: 1  # 1 MB max\n      size_unit: megabytes\n\n  # 4. IP Restriction (admin endpoints)\n  - name: ip-restriction\n    service: admin-service\n    config:\n      allow:\n        - 10.0.0.0\u002F8\n        - 172.16.0.0\u002F12\n\n  # 5. Bot Detection\n  - name: bot-detection\n    config:\n      deny:\n        - \"sqlmap\"\n        - \"nikto\"\n        - \"nmap\"\n        - \"masscan\"\n\n  # 6. CORS Configuration\n  - name: cors\n    config:\n      origins:\n        - \"https:\u002F\u002Fapp.example.com\"\n      methods:\n        - GET\n        - POST\n        - PUT\n        - PATCH\n        - DELETE\n      headers:\n        - Authorization\n        - Content-Type\n      credentials: true\n      max_age: 3600\n\n  # 7. Response Transformer - Remove sensitive headers\n  - name: response-transformer\n    config:\n      remove:\n        headers:\n          - X-Powered-By\n          - Server\n      add:\n        headers:\n          - \"X-Content-Type-Options: nosniff\"\n          - \"X-Frame-Options: DENY\"\n          - \"Strict-Transport-Security: max-age=31536000; includeSubDomains\"\n          - \"Content-Security-Policy: default-src 'none'\"\n```\n\n### Step 2: AWS API Gateway Security Configuration\n\n```python\nimport boto3\nimport json\n\napigw = boto3.client('apigatewayv2')\n\n# Create API with mutual TLS\napi_response = apigw.create_api(\n    Name='secure-api',\n    ProtocolType='HTTP',\n    DisableExecuteApiEndpoint=True,  # Force custom domain\n)\napi_id = api_response['ApiId']\n\n# Configure authorizer (JWT with Cognito)\nauthorizer = apigw.create_authorizer(\n    ApiId=api_id,\n    AuthorizerType='JWT',\n    IdentitySource='$request.header.Authorization',\n    Name='cognito-jwt-authorizer',\n    JwtConfiguration={\n        'Audience': ['your-app-client-id'],\n        'Issuer': 'https:\u002F\u002Fcognito-idp.us-east-1.amazonaws.com\u002Fus-east-1_xxxxx'\n    }\n)\n\n# Create route with authorizer\napigw.create_route(\n    ApiId=api_id,\n    RouteKey='GET \u002Fapi\u002Fv1\u002Fusers',\n    AuthorizerId=authorizer['AuthorizerId'],\n    AuthorizationType='JWT',\n)\n\n# Configure throttling\napigw.create_stage(\n    ApiId=api_id,\n    StageName='prod',\n    DefaultRouteSettings={\n        'ThrottlingBurstLimit': 100,\n        'ThrottlingRateLimit': 50.0,  # 50 requests per second\n    },\n    AccessLogSettings={\n        'DestinationArn': 'arn:aws:logs:us-east-1:123456789:log-group:api-access-logs',\n        'Format': json.dumps({\n            'requestId': '$context.requestId',\n            'ip': '$context.identity.sourceIp',\n            'caller': '$context.identity.caller',\n            'user': '$context.identity.user',\n            'requestTime': '$context.requestTime',\n            'httpMethod': '$context.httpMethod',\n            'resourcePath': '$context.resourcePath',\n            'status': '$context.status',\n            'protocol': '$context.protocol',\n            'responseLength': '$context.responseLength'\n        })\n    }\n)\n\n# WAF association\nwaf = boto3.client('wafv2')\nweb_acl = waf.create_web_acl(\n    Name='api-security-acl',\n    Scope='REGIONAL',\n    DefaultAction={'Allow': {}},\n    Rules=[\n        {\n            'Name': 'AWS-AWSManagedRulesSQLiRuleSet',\n            'Priority': 1,\n            'Statement': {\n                'ManagedRuleGroupStatement': {\n                    'VendorName': 'AWS',\n                    'Name': 'AWSManagedRulesSQLiRuleSet'\n                }\n            },\n            'OverrideAction': {'None': {}},\n            'VisibilityConfig': {\n                'SampledRequestsEnabled': True,\n                'CloudWatchMetricsEnabled': True,\n                'MetricName': 'SQLiRuleSet'\n            }\n        },\n        {\n            'Name': 'RateLimit',\n            'Priority': 2,\n            'Statement': {\n                'RateBasedStatement': {\n                    'Limit': 2000,\n                    'AggregateKeyType': 'IP'\n                }\n            },\n            'Action': {'Block': {}},\n            'VisibilityConfig': {\n                'SampledRequestsEnabled': True,\n                'CloudWatchMetricsEnabled': True,\n                'MetricName': 'RateLimitRule'\n            }\n        },\n    ],\n    VisibilityConfig={\n        'SampledRequestsEnabled': True,\n        'CloudWatchMetricsEnabled': True,\n        'MetricName': 'ApiSecurityACL'\n    }\n)\n```\n\n### Step 3: Request Validation with OpenAPI Schema\n\n```yaml\n# Kong OAS Validation Plugin configuration\nplugins:\n  - name: oas-validation\n    config:\n      api_spec: |\n        openapi: \"3.0.3\"\n        info:\n          title: Secure API\n          version: \"1.0\"\n        paths:\n          \u002Fapi\u002Fv1\u002Fusers:\n            post:\n              requestBody:\n                required: true\n                content:\n                  application\u002Fjson:\n                    schema:\n                      type: object\n                      required: [name, email]\n                      properties:\n                        name:\n                          type: string\n                          maxLength: 100\n                          pattern: \"^[a-zA-Z ]+$\"\n                        email:\n                          type: string\n                          format: email\n                          maxLength: 255\n                      additionalProperties: false  # Block mass assignment\n              responses:\n                '201':\n                  description: User created\n      validate_request_body: true\n      validate_request_header_params: true\n      validate_request_query_params: true\n      validate_request_uri_params: true\n      verbose_response: false  # Do not expose schema details in errors\n```\n\n### Step 4: Mutual TLS Configuration\n\n```bash\n# Generate CA and client certificates for mTLS\n# 1. Create CA\nopenssl genrsa -out ca.key 4096\nopenssl req -new -x509 -key ca.key -out ca.crt -days 365 \\\n    -subj \"\u002FCN=API Gateway CA\u002FO=Example Corp\"\n\n# 2. Create client certificate\nopenssl genrsa -out client.key 2048\nopenssl req -new -key client.key -out client.csr \\\n    -subj \"\u002FCN=api-client\u002FO=Example Corp\"\nopenssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key \\\n    -CAcreateserial -out client.crt -days 365\n\n# Kong mTLS configuration\n# Upload CA certificate to Kong\ncurl -X POST http:\u002F\u002Fkong-admin:8001\u002Fca_certificates \\\n    -F \"cert=@ca.crt\"\n\n# Enable mTLS plugin\ncurl -X POST http:\u002F\u002Fkong-admin:8001\u002Fservices\u002Fuser-service\u002Fplugins \\\n    --data \"name=mtls-auth\" \\\n    --data \"config.ca_certificates[]=$(cat ca_cert_id)\" \\\n    --data \"config.revocation_check_mode=SKIP\" \\\n    --data \"config.authenticated_group_by=CN\"\n```\n\n### Step 5: Logging and Monitoring Configuration\n\n```python\n# CloudWatch monitoring for API security events\nimport boto3\n\ncloudwatch = boto3.client('cloudwatch')\nlogs = boto3.client('logs')\n\n# Create metric filters for security events\nsecurity_filters = [\n    {\n        'name': 'UnauthorizedAccess',\n        'pattern': '{ $.status = 401 || $.status = 403 }',\n        'metric': 'UnauthorizedAccessCount'\n    },\n    {\n        'name': 'RateLimitHits',\n        'pattern': '{ $.status = 429 }',\n        'metric': 'RateLimitHitCount'\n    },\n    {\n        'name': 'ServerErrors',\n        'pattern': '{ $.status >= 500 }',\n        'metric': 'ServerErrorCount'\n    },\n    {\n        'name': 'LargeResponses',\n        'pattern': '{ $.responseLength > 1000000 }',\n        'metric': 'LargeResponseCount'\n    },\n]\n\nfor sf in security_filters:\n    logs.put_metric_filter(\n        logGroupName='api-access-logs',\n        filterName=sf['name'],\n        filterPattern=sf['pattern'],\n        metricTransformations=[{\n            'metricName': sf['metric'],\n            'metricNamespace': 'APISecurityMetrics',\n            'metricValue': '1',\n            'defaultValue': 0\n        }]\n    )\n\n# Create alarm for unusual 401\u002F403 spike\ncloudwatch.put_metric_alarm(\n    AlarmName='API-UnauthorizedAccessSpike',\n    MetricName='UnauthorizedAccessCount',\n    Namespace='APISecurityMetrics',\n    Statistic='Sum',\n    Period=300,  # 5 minutes\n    EvaluationPeriods=1,\n    Threshold=100,\n    ComparisonOperator='GreaterThanThreshold',\n    AlarmActions=['arn:aws:sns:us-east-1:123456789:security-alerts'],\n    AlarmDescription='More than 100 unauthorized access attempts in 5 minutes'\n)\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| **API Gateway** | Centralized entry point for all API traffic that enforces authentication, authorization, rate limiting, and request validation before routing to backend services |\n| **Rate Limiting** | Controlling the number of API requests per client within a time window to prevent abuse and ensure fair resource allocation |\n| **Request Validation** | Verifying that incoming API requests conform to the expected schema (data types, required fields, value ranges) before forwarding to backend services |\n| **Mutual TLS (mTLS)** | Two-way TLS authentication where both the client and server present certificates, providing strong identity verification for API-to-API communication |\n| **WAF Integration** | Web Application Firewall rules applied at the API gateway to block common attack patterns (SQLi, XSS, path traversal) |\n| **OAuth2\u002FOIDC** | Token-based authentication protocols where the gateway validates JWT tokens against an identity provider before allowing access |\n\n## Tools & Systems\n\n- **Kong Gateway**: Open-source API gateway with extensive plugin ecosystem for security, rate limiting, and authentication\n- **AWS API Gateway**: Managed API gateway service with built-in throttling, WAF integration, and Lambda authorizers\n- **Azure API Management**: Enterprise API gateway with policy-based security, developer portal, and Azure AD integration\n- **Apigee (Google Cloud)**: API management platform with threat protection, quota management, and API analytics\n- **Envoy Proxy**: High-performance proxy used as API gateway in service mesh architectures with extensive filter chain\n\n## Common Scenarios\n\n### Scenario: Securing a Microservice API with Kong Gateway\n\n**Context**: A company is migrating from a monolithic API to microservices. Each microservice has its own REST API. The security team needs to implement centralized authentication, rate limiting, and request validation without modifying each service.\n\n**Approach**:\n1. Deploy Kong Gateway as the single entry point, routing traffic to 8 backend microservices\n2. Configure JWT validation plugin to verify tokens against the company's Keycloak IdP\n3. Apply rate limiting: 60 requests\u002Fminute for regular users, 300\u002Fminute for premium users, identified by JWT claims\n4. Enable OAS validation plugin to reject requests that do not match the OpenAPI spec (blocks mass assignment and injection)\n5. Configure mTLS for service-to-service communication behind the gateway\n6. Set up response transformer to remove Server and X-Powered-By headers and add security headers\n7. Integrate with AWS WAF for SQL injection and XSS protection rules\n8. Configure access logging to CloudWatch with security metric filters and alerting\n\n**Pitfalls**:\n- Relying solely on the gateway for authorization when backend services also need to verify permissions\n- Not configuring rate limiting per authenticated user (per-IP only allows attackers to bypass with IP rotation)\n- Using verbose error responses from the gateway that reveal internal service architecture\n- Not testing the gateway configuration with security tools after deployment\n- Missing mutual TLS between the gateway and backend services, allowing direct backend access\n\n## Output Format\n\n```\n## API Gateway Security Configuration Report\n\n**Gateway**: Kong 3.5 (Kubernetes deployment)\n**Backend Services**: 8 microservices\n**Date**: 2024-12-15\n\n### Security Controls Implemented\n\n| Control | Plugin\u002FFeature | Configuration |\n|---------|---------------|---------------|\n| Authentication | JWT Plugin | Cognito IdP, 1-hour max TTL |\n| Rate Limiting | Rate Limiting Plugin | 60 req\u002Fmin (user), Redis-backed |\n| Request Validation | OAS Validation | Strict mode, no additional properties |\n| TLS | Kong TLS | TLS 1.3 only, HSTS enabled |\n| mTLS | mTLS Auth Plugin | Client cert required for admin APIs |\n| WAF | AWS WAF | SQLi, XSS, rate-based rules |\n| Headers | Response Transformer | Server header removed, security headers added |\n| Logging | HTTP Log Plugin | CloudWatch, security metric filters |\n\n### Verification Results\n\n- JWT validation: Expired\u002Finvalid tokens correctly rejected (tested 50 payloads)\n- Rate limiting: Enforced at 60 req\u002Fmin, 429 returned with Retry-After header\n- Request validation: Malformed requests rejected with 400 (tested 30 invalid payloads)\n- mTLS: Requests without client certificate rejected with 401\n- WAF: SQL injection payloads blocked (tested top 100 SQLi patterns)\n```\n","# Implementing API Gateway Security Controls\n\n## When to Use\n\n- Deploying a centralized authentication and authorization layer for microservice APIs\n- Implementing rate limiting, throttling, and quota management across all API endpoints\n- Configuring request\u002Fresponse validation against OpenAPI specifications at the gateway level\n- Setting up TLS termination, mutual TLS, and certificate management for API traffic\n- Integrating WAF rules with the API gateway to block injection, XSS, and known attack patterns\n\n**Do not use** as the sole security layer. API gateways provide defense in depth but backend services must also validate authorization and input.\n\n## Prerequisites\n\n- API gateway platform selected and deployed (Kong, AWS API Gateway, Azure APIM, or Apigee)\n- OpenAPI\u002FSwagger specifications for all backend APIs\n- TLS certificates for the gateway domain\n- Identity provider (IdP) configured for OAuth2\u002FOIDC (Okta, Auth0, Azure AD)\n- Monitoring and logging infrastructure (CloudWatch, Datadog, ELK)\n- Backend service endpoints registered and reachable from the gateway\n\n## Workflow\n\n### Step 1: Kong Gateway Security Configuration\n\n```yaml\n# kong.yml - Declarative Kong configuration with security plugins\n_format_version: \"3.0\"\n\nservices:\n  - name: user-service\n    url: http:\u002F\u002Fuser-service:8080\n    routes:\n      - name: user-api\n        paths:\n          - \u002Fapi\u002Fv1\u002Fusers\n        methods:\n          - GET\n          - POST\n          - PUT\n          - PATCH\n          - DELETE\n        strip_path: false\n\nplugins:\n  # 1. Authentication: JWT validation\n  - name: jwt\n    config:\n      uri_param_names:\n        - jwt\n      header_names:\n        - Authorization\n      claims_to_verify:\n        - exp\n      maximum_expiration: 3600  # Max 1 hour token TTL\n\n  # 2. Rate Limiting\n  - name: rate-limiting\n    config:\n      minute: 60\n      hour: 1000\n      policy: redis\n      redis_host: redis\n      redis_port: 6379\n      fault_tolerant: true\n      hide_client_headers: false\n      limit_by: credential  # Per-user, not per-IP\n\n  # 3. Request Size Limiting\n  - name: request-size-limiting\n    config:\n      allowed_payload_size: 1  # 1 MB max\n      size_unit: megabytes\n\n  # 4. IP Restriction (admin endpoints)\n  - name: ip-restriction\n    service: admin-service\n    config:\n      allow:\n        - 10.0.0.0\u002F8\n        - 172.16.0.0\u002F12\n\n  # 5. Bot Detection\n  - name: bot-detection\n    config:\n      deny:\n        - \"sqlmap\"\n        - \"nikto\"\n        - \"nmap\"\n        - \"masscan\"\n\n  # 6. CORS Configuration\n  - name: cors\n    config:\n      origins:\n        - \"https:\u002F\u002Fapp.example.com\"\n      methods:\n        - GET\n        - POST\n        - PUT\n        - PATCH\n        - DELETE\n      headers:\n        - Authorization\n        - Content-Type\n      credentials: true\n      max_age: 3600\n\n  # 7. Response Transformer - Remove sensitive headers\n  - name: response-transformer\n    config:\n      remove:\n        headers:\n          - X-Powered-By\n          - Server\n      add:\n        headers:\n          - \"X-Content-Type-Options: nosniff\"\n          - \"X-Frame-Options: DENY\"\n          - \"Strict-Transport-Security: max-age=31536000; includeSubDomains\"\n          - \"Content-Security-Policy: default-src 'none'\"\n```\n\n### Step 2: AWS API Gateway Security Configuration\n\n```python\nimport boto3\nimport json\n\napigw = boto3.client('apigatewayv2')\n\n# Create API with mutual TLS\napi_response = apigw.create_api(\n    Name='secure-api',\n    ProtocolType='HTTP',\n    DisableExecuteApiEndpoint=True,  # Force custom domain\n)\napi_id = api_response['ApiId']\n\n# Configure authorizer (JWT with Cognito)\nauthorizer = apigw.create_authorizer(\n    ApiId=api_id,\n    AuthorizerType='JWT',\n    IdentitySource='$request.header.Authorization',\n    Name='cognito-jwt-authorizer',\n    JwtConfiguration={\n        'Audience': ['your-app-client-id'],\n        'Issuer': 'https:\u002F\u002Fcognito-idp.us-east-1.amazonaws.com\u002Fus-east-1_xxxxx'\n    }\n)\n\n# Create route with authorizer\napigw.create_route(\n    ApiId=api_id,\n    RouteKey='GET \u002Fapi\u002Fv1\u002Fusers',\n    AuthorizerId=authorizer['AuthorizerId'],\n    AuthorizationType='JWT',\n)\n\n# Configure throttling\napigw.create_stage(\n    ApiId=api_id,\n    StageName='prod',\n    DefaultRouteSettings={\n        'ThrottlingBurstLimit': 100,\n        'ThrottlingRateLimit': 50.0,  # 50 requests per second\n    },\n    AccessLogSettings={\n        'DestinationArn': 'arn:aws:logs:us-east-1:123456789:log-group:api-access-logs',\n        'Format': json.dumps({\n            'requestId': '$context.requestId',\n            'ip': '$context.identity.sourceIp',\n            'caller': '$context.identity.caller',\n            'user': '$context.identity.user',\n            'requestTime': '$context.requestTime',\n            'httpMethod': '$context.httpMethod',\n            'resourcePath': '$context.resourcePath',\n            'status': '$context.status',\n            'protocol': '$context.protocol',\n            'responseLength': '$context.responseLength'\n        })\n    }\n)\n\n# WAF association\nwaf = boto3.client('wafv2')\nweb_acl = waf.create_web_acl(\n    Name='api-security-acl',\n    Scope='REGIONAL',\n    DefaultAction={'Allow': {}},\n    Rules=[\n        {\n            'Name': 'AWS-AWSManagedRulesSQLiRuleSet',\n            'Priority': 1,\n            'Statement': {\n                'ManagedRuleGroupStatement': {\n                    'VendorName': 'AWS',\n                    'Name': 'AWSManagedRulesSQLiRuleSet'\n                }\n            },\n            'OverrideAction': {'None': {}},\n            'VisibilityConfig': {\n                'SampledRequestsEnabled': True,\n                'CloudWatchMetricsEnabled': True,\n                'MetricName': 'SQLiRuleSet'\n            }\n        },\n        {\n            'Name': 'RateLimit',\n            'Priority': 2,\n            'Statement': {\n                'RateBasedStatement': {\n                    'Limit': 2000,\n                    'AggregateKeyType': 'IP'\n                }\n            },\n            'Action': {'Block': {}},\n            'VisibilityConfig': {\n                'SampledRequestsEnabled': True,\n                'CloudWatchMetricsEnabled': True,\n                'MetricName': 'RateLimitRule'\n            }\n        },\n    ],\n    VisibilityConfig={\n        'SampledRequestsEnabled': True,\n        'CloudWatchMetricsEnabled': True,\n        'MetricName': 'ApiSecurityACL'\n    }\n)\n```\n\n### Step 3: Request Validation with OpenAPI Schema\n\n```yaml\n# Kong OAS Validation Plugin configuration\nplugins:\n  - name: oas-validation\n    config:\n      api_spec: |\n        openapi: \"3.0.3\"\n        info:\n          title: Secure API\n          version: \"1.0\"\n        paths:\n          \u002Fapi\u002Fv1\u002Fusers:\n            post:\n              requestBody:\n                required: true\n                content:\n                  application\u002Fjson:\n                    schema:\n                      type: object\n                      required: [name, email]\n                      properties:\n                        name:\n                          type: string\n                          maxLength: 100\n                          pattern: \"^[a-zA-Z ]+$\"\n                        email:\n                          type: string\n                          format: email\n                          maxLength: 255\n                      additionalProperties: false  # Block mass assignment\n              responses:\n                '201':\n                  description: User created\n      validate_request_body: true\n      validate_request_header_params: true\n      validate_request_query_params: true\n      validate_request_uri_params: true\n      verbose_response: false  # Do not expose schema details in errors\n```\n\n### Step 4: Mutual TLS Configuration\n\n```bash\n# Generate CA and client certificates for mTLS\n# 1. Create CA\nopenssl genrsa -out ca.key 4096\nopenssl req -new -x509 -key ca.key -out ca.crt -days 365 \\\n    -subj \"\u002FCN=API Gateway CA\u002FO=Example Corp\"\n\n# 2. Create client certificate\nopenssl genrsa -out client.key 2048\nopenssl req -new -key client.key -out client.csr \\\n    -subj \"\u002FCN=api-client\u002FO=Example Corp\"\nopenssl x509 -req -in client.csr -CA ca.crt -CAkey ca.key \\\n    -CAcreateserial -out client.crt -days 365\n\n# Kong mTLS configuration\n# Upload CA certificate to Kong\ncurl -X POST http:\u002F\u002Fkong-admin:8001\u002Fca_certificates \\\n    -F \"cert=@ca.crt\"\n\n# Enable mTLS plugin\ncurl -X POST http:\u002F\u002Fkong-admin:8001\u002Fservices\u002Fuser-service\u002Fplugins \\\n    --data \"name=mtls-auth\" \\\n    --data \"config.ca_certificates[]=$(cat ca_cert_id)\" \\\n    --data \"config.revocation_check_mode=SKIP\" \\\n    --data \"config.authenticated_group_by=CN\"\n```\n\n### Step 5: Logging and Monitoring Configuration\n\n```python\n# CloudWatch monitoring for API security events\nimport boto3\n\ncloudwatch = boto3.client('cloudwatch')\nlogs = boto3.client('logs')\n\n# Create metric filters for security events\nsecurity_filters = [\n    {\n        'name': 'UnauthorizedAccess',\n        'pattern': '{ $.status = 401 || $.status = 403 }',\n        'metric': 'UnauthorizedAccessCount'\n    },\n    {\n        'name': 'RateLimitHits',\n        'pattern': '{ $.status = 429 }',\n        'metric': 'RateLimitHitCount'\n    },\n    {\n        'name': 'ServerErrors',\n        'pattern': '{ $.status >= 500 }',\n        'metric': 'ServerErrorCount'\n    },\n    {\n        'name': 'LargeResponses',\n        'pattern': '{ $.responseLength > 1000000 }',\n        'metric': 'LargeResponseCount'\n    },\n]\n\nfor sf in security_filters:\n    logs.put_metric_filter(\n        logGroupName='api-access-logs',\n        filterName=sf['name'],\n        filterPattern=sf['pattern'],\n        metricTransformations=[{\n            'metricName': sf['metric'],\n            'metricNamespace': 'APISecurityMetrics',\n            'metricValue': '1',\n            'defaultValue': 0\n        }]\n    )\n\n# Create alarm for unusual 401\u002F403 spike\ncloudwatch.put_metric_alarm(\n    AlarmName='API-UnauthorizedAccessSpike',\n    MetricName='UnauthorizedAccessCount',\n    Namespace='APISecurityMetrics',\n    Statistic='Sum',\n    Period=300,  # 5 minutes\n    EvaluationPeriods=1,\n    Threshold=100,\n    ComparisonOperator='GreaterThanThreshold',\n    AlarmActions=['arn:aws:sns:us-east-1:123456789:security-alerts'],\n    AlarmDescription='More than 100 unauthorized access attempts in 5 minutes'\n)\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| **API Gateway** | Centralized entry point for all API traffic that enforces authentication, authorization, rate limiting, and request validation before routing to backend services |\n| **Rate Limiting** | Controlling the number of API requests per client within a time window to prevent abuse and ensure fair resource allocation |\n| **Request Validation** | Verifying that incoming API requests conform to the expected schema (data types, required fields, value ranges) before forwarding to backend services |\n| **Mutual TLS (mTLS)** | Two-way TLS authentication where both the client and server present certificates, providing strong identity verification for API-to-API communication |\n| **WAF Integration** | Web Application Firewall rules applied at the API gateway to block common attack patterns (SQLi, XSS, path traversal) |\n| **OAuth2\u002FOIDC** | Token-based authentication protocols where the gateway validates JWT tokens against an identity provider before allowing access |\n\n## Tools & Systems\n\n- **Kong Gateway**: Open-source API gateway with extensive plugin ecosystem for security, rate limiting, and authentication\n- **AWS API Gateway**: Managed API gateway service with built-in throttling, WAF integration, and Lambda authorizers\n- **Azure API Management**: Enterprise API gateway with policy-based security, developer portal, and Azure AD integration\n- **Apigee (Google Cloud)**: API management platform with threat protection, quota management, and API analytics\n- **Envoy Proxy**: High-performance proxy used as API gateway in service mesh architectures with extensive filter chain\n\n## Common Scenarios\n\n### Scenario: Securing a Microservice API with Kong Gateway\n\n**Context**: A company is migrating from a monolithic API to microservices. Each microservice has its own REST API. The security team needs to implement centralized authentication, rate limiting, and request validation without modifying each service.\n\n**Approach**:\n1. Deploy Kong Gateway as the single entry point, routing traffic to 8 backend microservices\n2. Configure JWT validation plugin to verify tokens against the company's Keycloak IdP\n3. Apply rate limiting: 60 requests\u002Fminute for regular users, 300\u002Fminute for premium users, identified by JWT claims\n4. Enable OAS validation plugin to reject requests that do not match the OpenAPI spec (blocks mass assignment and injection)\n5. Configure mTLS for service-to-service communication behind the gateway\n6. Set up response transformer to remove Server and X-Powered-By headers and add security headers\n7. Integrate with AWS WAF for SQL injection and XSS protection rules\n8. Configure access logging to CloudWatch with security metric filters and alerting\n\n**Pitfalls**:\n- Relying solely on the gateway for authorization when backend services also need to verify permissions\n- Not configuring rate limiting per authenticated user (per-IP only allows attackers to bypass with IP rotation)\n- Using verbose error responses from the gateway that reveal internal service architecture\n- Not testing the gateway configuration with security tools after deployment\n- Missing mutual TLS between the gateway and backend services, allowing direct backend access\n\n## Output Format\n\n```\n## API Gateway Security Configuration Report\n\n**Gateway**: Kong 3.5 (Kubernetes deployment)\n**Backend Services**: 8 microservices\n**Date**: 2024-12-15\n\n### Security Controls Implemented\n\n| Control | Plugin\u002FFeature | Configuration |\n|---------|---------------|---------------|\n| Authentication | JWT Plugin | Cognito IdP, 1-hour max TTL |\n| Rate Limiting | Rate Limiting Plugin | 60 req\u002Fmin (user), Redis-backed |\n| Request Validation | OAS Validation | Strict mode, no additional properties |\n| TLS | Kong TLS | TLS 1.3 only, HSTS enabled |\n| mTLS | mTLS Auth Plugin | Client cert required for admin APIs |\n| WAF | AWS WAF | SQLi, XSS, rate-based rules |\n| Headers | Response Transformer | Server header removed, security headers added |\n| Logging | HTTP Log Plugin | CloudWatch, security metric filters |\n\n### Verification Results\n\n- JWT validation: Expired\u002Finvalid tokens correctly rejected (tested 50 payloads)\n- Rate limiting: Enforced at 60 req\u002Fmin, 429 returned with Retry-After header\n- Request validation: Malformed requests rejected with 400 (tested 30 invalid payloads)\n- mTLS: Requests without client certificate rejected with 401\n- WAF: SQL injection payloads blocked (tested top 100 SQLi patterns)\n```\n",{"name":5,"tags":57,"author":59,"domain":51,"license":15,"version":60,"nist_csf":61,"subdomain":44,"description":7,"mitre_attack":66},[44,37,42,43,58,36],"rate-limiting","mahipal","1.0.0",[62,63,64,65],"PR.PS-01","ID.RA-01","PR.DS-10","DE.CM-01",[67,68,69,70,71],"T1190","T1059.007","T1552.001","T1078.004","T1530","main","54a798831d2266a3ca61ce68a7acb80b81160d57","skills\u002Fimplementing-api-gateway-security-controls",4395,"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":83,"prompt":93,"zipAvailable":94},[84,87,90],{"tool":85,"command":86},"npx","npx skills add mukul975\u002FAnthropic-Cybersecurity-Skills --skill implementing-api-gateway-security-controls",{"tool":88,"command":89},"bunx","bunx skills add mukul975\u002FAnthropic-Cybersecurity-Skills --skill implementing-api-gateway-security-controls",{"tool":91,"command":92},"pnpm","pnpm dlx skills add mukul975\u002FAnthropic-Cybersecurity-Skills --skill implementing-api-gateway-security-controls","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-gateway-security-controls\u002FSKILL.md",true,[96,101,107],{"path":97,"resourceType":97,"resourceTypeDesc":98,"sizeBytes":99,"sourceHtmlUrl":100},"LICENSE","许可证",11255,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-gateway-security-controls\u002FLICENSE",{"path":102,"resourceType":103,"resourceTypeDesc":104,"sizeBytes":105,"sourceHtmlUrl":106},"references\u002Fapi-reference.md","REFERENCE","参考文档",1638,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-gateway-security-controls\u002Freferences\u002Fapi-reference.md",{"path":108,"resourceType":109,"resourceTypeDesc":110,"sizeBytes":111,"sourceHtmlUrl":112},"scripts\u002Fagent.py","SCRIPT","脚本",6527,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-gateway-security-controls\u002Fscripts\u002Fagent.py",[114,139,163,189,215,242],{"skillNo":115,"name":116,"nameZh":6,"description":117,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":118,"categories":119,"keywords":121,"publishedAt":52},"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",[120],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[122,123,124,125,35,51,126,127,49,128,129,130,131,132,133,134,135,136,137,138],"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":140,"name":141,"nameZh":6,"description":142,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":143,"categories":144,"keywords":146,"publishedAt":52},"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",[145],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[147,135,148,149,35,150,51,49,151,152,153,154,155,156,157,158,159,160,161,162],"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":164,"name":165,"nameZh":6,"description":166,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":167,"categories":168,"keywords":173,"publishedAt":52},"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",[169,172],{"categoryNo":170,"categoryName":171,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000008","测试与质量",{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[157,174,175,176,177,51,178,47,151,179,180,181,182,183,184,39,185,186,187,188],"backup","recovery","validating backup integrity for recovery","testing","infrastructure","compliance","hash-verification","incident-response","ransomware","cryptocurrency","detection","t1490","immutable","disaster-recovery","restore-testing",{"skillNo":190,"name":191,"nameZh":6,"description":192,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":193,"categories":194,"keywords":196,"publishedAt":52},"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",[195],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[197,198,199,51,200,201,202,203,204,205,206,207,208,209,210,211,154,212,213,214],"windows","kape","triaging windows with kape","registry","browser","logs","windows-forensics","dfir","mft","mftecmd","data","prefetch","eric-zimmerman","digital-forensics","SET","collection","pecmd","artifact-collection",{"skillNo":216,"name":217,"nameZh":6,"description":218,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":219,"categories":220,"keywords":222,"publishedAt":52},"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",[221],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[223,224,225,51,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241],"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":243,"name":244,"nameZh":6,"description":245,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":246,"categories":247,"keywords":249,"publishedAt":52},"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",[248],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[35,250,51,251,252,253,254,255,256,257,258,39,259,185,260,261,262,263,264,265],"triaging security incident","siem","file","ioc","soc","NIST-800-61","NIST","severity","edr","execution","analysis","classification","severity-classification","incident-triage","SANS-PICERL","SOC-operations"]