[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6AEYVK7CYZ9NDRA0636X5KY":3,"skill-same:01M6AEYVK7CYZ9NDRA0636X5KY":109},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":8,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":18,"categories":19,"keywords":30,"publishedAt":49,"linkOnly":50,"markdownContent":51,"markdownBody":52,"frontMatter":53,"refName":68,"commitSha":69,"skillDirectory":70,"forksCount":71,"repositoryHtmlUrl":72,"repositoryHomepageUrl":73,"ownerHtmlUrl":74,"ownerBlogUrl":75,"ownerDescription":76,"updatedAt":77,"install":78,"resources":91},"01M6AEYVK7CYZ9NDRA0636X5KY","implementing-api-rate-limiting-and-throttling","API 限流与节流实现","Implements API rate limiting and throttling with token bucket, sliding window, and fixed window algorithms, configuring per-user, per-IP, and per-endpoint limits via Redis-backed counters, API gateway plugins, or middleware, and returning proper HTTP 429 responses with Retry-After headers. Use when setting up request quota management or preventing brute force, credential stuffing, and resource exhaustion attacks against APIs.","使用令牌桶、滑动窗口和固定窗口算法实现 API 限流与节流，通过 Redis 计数器、API 网关插件或中间件配置按用户、按 IP、按端点的限流规则，并返回带有 Retry-After 头的 HTTP 429 响应。适用于设置请求配额管理，或防范针对 API 的暴力破解、凭证填充和资源耗尽攻击。","mukul975\u002FAnthropic-Cybersecurity-Skills","mukul975","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F42860185?v=4","01M6ADEQR8T5M4EEG6C67BQCWF","Mahipal","01M6ADJPMYWG1E5GM1FWBE3128",36146,"Apache-2.0",null,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-rate-limiting-and-throttling\u002FSKILL.md",[20,25],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BR4MYFKGCC4WCWVJ50KJ2C","安全工程师","PROFESSION","适用职业",{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BS1P5QP54ZNEBFHBTV293T","API 网关配置与管理","SCENARIO","使用场景",[31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48],"implementing api rate limiting and throttling","endpoint","abuse-prevention","throttling","token-bucket","prevention","t1059","t1003","rate-limiting","security","api-security","redis","plugins","gateway","api gateway","pr","http","cybersecurity","2026-11-10 10:12:30",false,"---\nname: implementing-api-rate-limiting-and-throttling\ndescription: 'Implements API rate limiting and throttling with token bucket, sliding\n  window, and fixed window algorithms, configuring per-user, per-IP, and per-endpoint\n  limits via Redis-backed counters, API gateway plugins, or middleware, and returning\n  proper HTTP 429 responses with Retry-After headers. Use when setting up request\n  quota management or preventing brute force, credential stuffing, and resource exhaustion\n  attacks against APIs.'\ndomain: cybersecurity\nsubdomain: api-security\ntags:\n- api-security\n- rate-limiting\n- throttling\n- redis\n- token-bucket\n- abuse-prevention\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- T1003\n- T1110\n---\n# Implementing API Rate Limiting and Throttling\n\n## When to Use\n\n- Protecting authentication endpoints against brute force and credential stuffing attacks\n- Preventing API abuse and resource exhaustion from automated scripts and bots\n- Implementing fair usage quotas for different API consumer tiers (free, premium, enterprise)\n- Defending against denial-of-service attacks at the application layer\n- Meeting compliance requirements that mandate API abuse prevention controls\n\n**Do not use** rate limiting as the sole defense against attacks. Combine with authentication, authorization, and WAF rules.\n\n## Prerequisites\n\n- Redis 6.0+ for distributed rate limit counters (or in-memory for single-instance deployments)\n- API framework (Express.js, FastAPI, Spring Boot, or Django REST Framework)\n- Monitoring system for rate limit metrics (Prometheus, CloudWatch, Datadog)\n- Understanding of the API's normal traffic patterns and peak usage\n- Load testing tool (k6, Gatling, or Locust) for validating rate limit behavior\n\n## Workflow\n\n### Step 1: Rate Limiting Strategy Design\n\nDefine rate limits per endpoint category and user tier:\n\n```python\n# Rate limit configuration\nRATE_LIMITS = {\n    # Authentication endpoints (most restrictive)\n    \"auth\": {\n        \"login\": {\"requests\": 5, \"window_seconds\": 60, \"by\": \"ip\"},\n        \"register\": {\"requests\": 3, \"window_seconds\": 300, \"by\": \"ip\"},\n        \"forgot_password\": {\"requests\": 3, \"window_seconds\": 3600, \"by\": \"ip\"},\n        \"verify_mfa\": {\"requests\": 5, \"window_seconds\": 300, \"by\": \"user\"},\n    },\n    # Standard API endpoints\n    \"api\": {\n        \"free\": {\"requests\": 60, \"window_seconds\": 60, \"by\": \"user\"},\n        \"premium\": {\"requests\": 300, \"window_seconds\": 60, \"by\": \"user\"},\n        \"enterprise\": {\"requests\": 1000, \"window_seconds\": 60, \"by\": \"user\"},\n    },\n    # Resource-intensive endpoints\n    \"expensive\": {\n        \"search\": {\"requests\": 10, \"window_seconds\": 60, \"by\": \"user\"},\n        \"export\": {\"requests\": 5, \"window_seconds\": 3600, \"by\": \"user\"},\n        \"bulk_import\": {\"requests\": 2, \"window_seconds\": 3600, \"by\": \"user\"},\n    },\n    # Global limits\n    \"global\": {\n        \"per_ip\": {\"requests\": 1000, \"window_seconds\": 60, \"by\": \"ip\"},\n        \"per_user\": {\"requests\": 5000, \"window_seconds\": 3600, \"by\": \"user\"},\n    },\n}\n```\n\n### Step 2: Sliding Window Rate Limiter (Redis)\n\n```python\nimport redis\nimport time\nimport hashlib\nfrom functools import wraps\nfrom flask import Flask, request, jsonify, g\n\napp = Flask(__name__)\nredis_client = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)\n\nclass SlidingWindowRateLimiter:\n    \"\"\"Sliding window rate limiter using Redis sorted sets.\"\"\"\n\n    def __init__(self, redis_conn):\n        self.redis = redis_conn\n\n    def is_allowed(self, key, max_requests, window_seconds):\n        \"\"\"Check if request is allowed and record it.\"\"\"\n        now = time.time()\n        window_start = now - window_seconds\n        pipe = self.redis.pipeline()\n\n        # Remove expired entries\n        pipe.zremrangebyscore(key, 0, window_start)\n        # Count requests in current window\n        pipe.zcard(key)\n        # Add current request\n        pipe.zadd(key, {f\"{now}:{hashlib.md5(str(now).encode()).hexdigest()[:8]}\": now})\n        # Set TTL on the key\n        pipe.expire(key, window_seconds + 1)\n\n        results = pipe.execute()\n        current_count = results[1]\n\n        if current_count >= max_requests:\n            # Calculate retry-after\n            oldest = self.redis.zrange(key, 0, 0, withscores=True)\n            if oldest:\n                retry_after = int(oldest[0][1] + window_seconds - now) + 1\n            else:\n                retry_after = window_seconds\n            return False, current_count, max_requests, retry_after\n\n        return True, current_count + 1, max_requests, 0\n\nrate_limiter = SlidingWindowRateLimiter(redis_client)\n\ndef rate_limit(max_requests, window_seconds, key_func=None):\n    \"\"\"Decorator for rate limiting API endpoints.\"\"\"\n    def decorator(f):\n        @wraps(f)\n        def wrapped(*args, **kwargs):\n            # Determine the rate limit key\n            if key_func:\n                identifier = key_func()\n            elif hasattr(g, 'user_id'):\n                identifier = f\"user:{g.user_id}\"\n            else:\n                identifier = f\"ip:{request.remote_addr}\"\n\n            key = f\"ratelimit:{request.endpoint}:{identifier}\"\n            allowed, current, limit, retry_after = rate_limiter.is_allowed(\n                key, max_requests, window_seconds)\n\n            # Always set rate limit headers\n            headers = {\n                \"X-RateLimit-Limit\": str(limit),\n                \"X-RateLimit-Remaining\": str(max(0, limit - current)),\n                \"X-RateLimit-Reset\": str(int(time.time()) + window_seconds),\n            }\n\n            if not allowed:\n                headers[\"Retry-After\"] = str(retry_after)\n                response = jsonify({\n                    \"error\": \"rate_limit_exceeded\",\n                    \"message\": \"Too many requests. Please try again later.\",\n                    \"retry_after\": retry_after\n                })\n                response.status_code = 429\n                for h, v in headers.items():\n                    response.headers[h] = v\n                return response\n\n            response = f(*args, **kwargs)\n            for h, v in headers.items():\n                response.headers[h] = v\n            return response\n        return wrapped\n    return decorator\n\n# Apply rate limiting to endpoints\n@app.route('\u002Fapi\u002Fv1\u002Fauth\u002Flogin', methods=['POST'])\n@rate_limit(max_requests=5, window_seconds=60,\n            key_func=lambda: f\"ip:{request.remote_addr}\")\ndef login():\n    # Login logic\n    return jsonify({\"message\": \"Login successful\"})\n\n@app.route('\u002Fapi\u002Fv1\u002Fusers\u002Fme', methods=['GET'])\n@rate_limit(max_requests=60, window_seconds=60)\ndef get_profile():\n    # Profile logic\n    return jsonify({\"user\": \"data\"})\n\n@app.route('\u002Fapi\u002Fv1\u002Fsearch', methods=['GET'])\n@rate_limit(max_requests=10, window_seconds=60)\ndef search():\n    # Search logic\n    return jsonify({\"results\": []})\n```\n\n### Step 3: Token Bucket Rate Limiter\n\n```python\nimport redis\nimport time\n\nclass TokenBucketRateLimiter:\n    \"\"\"Token bucket rate limiter allowing burst traffic within limits.\"\"\"\n\n    def __init__(self, redis_conn):\n        self.redis = redis_conn\n\n    def is_allowed(self, key, max_tokens, refill_rate, refill_interval=1):\n        \"\"\"\n        Token bucket algorithm:\n        - max_tokens: Maximum burst capacity\n        - refill_rate: Tokens added per refill_interval\n        - refill_interval: Seconds between refills\n        \"\"\"\n        now = time.time()\n        bucket_key = f\"tb:{key}\"\n\n        # Lua script for atomic token bucket operation\n        lua_script = \"\"\"\n        local key = KEYS[1]\n        local max_tokens = tonumber(ARGV[1])\n        local refill_rate = tonumber(ARGV[2])\n        local refill_interval = tonumber(ARGV[3])\n        local now = tonumber(ARGV[4])\n\n        local bucket = redis.call('hmget', key, 'tokens', 'last_refill')\n        local tokens = tonumber(bucket[1])\n        local last_refill = tonumber(bucket[2])\n\n        if tokens == nil then\n            tokens = max_tokens\n            last_refill = now\n        end\n\n        -- Refill tokens\n        local elapsed = now - last_refill\n        local refills = math.floor(elapsed \u002F refill_interval)\n        if refills > 0 then\n            tokens = math.min(max_tokens, tokens + (refills * refill_rate))\n            last_refill = last_refill + (refills * refill_interval)\n        end\n\n        local allowed = 0\n        if tokens >= 1 then\n            tokens = tokens - 1\n            allowed = 1\n        end\n\n        redis.call('hmset', key, 'tokens', tokens, 'last_refill', last_refill)\n        redis.call('expire', key, math.ceil(max_tokens \u002F refill_rate * refill_interval) + 10)\n\n        return {allowed, tokens, max_tokens}\n        \"\"\"\n\n        result = self.redis.eval(lua_script, 1, bucket_key,\n                                  max_tokens, refill_rate, refill_interval, now)\n        allowed = bool(result[0])\n        remaining = int(result[1])\n        limit = int(result[2])\n\n        return allowed, remaining, limit\n```\n\n### Step 4: Tiered Rate Limiting with User Plans\n\n```python\nfrom enum import Enum\n\nclass UserTier(Enum):\n    FREE = \"free\"\n    PREMIUM = \"premium\"\n    ENTERPRISE = \"enterprise\"\n\nTIER_LIMITS = {\n    UserTier.FREE: {\n        \"default\": (60, 60),          # 60 req\u002Fmin\n        \"search\": (10, 60),           # 10 req\u002Fmin\n        \"export\": (5, 3600),          # 5 req\u002Fhour\n        \"daily_total\": (1000, 86400), # 1000 req\u002Fday\n    },\n    UserTier.PREMIUM: {\n        \"default\": (300, 60),\n        \"search\": (50, 60),\n        \"export\": (20, 3600),\n        \"daily_total\": (10000, 86400),\n    },\n    UserTier.ENTERPRISE: {\n        \"default\": (1000, 60),\n        \"search\": (200, 60),\n        \"export\": (100, 3600),\n        \"daily_total\": (100000, 86400),\n    },\n}\n\ndef get_rate_limit_for_request(user_tier, endpoint_category=\"default\"):\n    \"\"\"Get rate limit configuration based on user tier and endpoint.\"\"\"\n    tier_config = TIER_LIMITS.get(user_tier, TIER_LIMITS[UserTier.FREE])\n    limit_config = tier_config.get(endpoint_category, tier_config[\"default\"])\n    return limit_config  # (max_requests, window_seconds)\n\nclass TieredRateLimitMiddleware:\n    \"\"\"Middleware that applies rate limits based on user subscription tier.\"\"\"\n\n    def __init__(self, app, redis_conn):\n        self.app = app\n        self.limiter = SlidingWindowRateLimiter(redis_conn)\n\n    def __call__(self, environ, start_response):\n        # Extract user info from request\n        user_id = environ.get(\"HTTP_X_USER_ID\")\n        user_tier = UserTier(environ.get(\"HTTP_X_USER_TIER\", \"free\"))\n        endpoint = environ.get(\"PATH_INFO\", \"\u002F\")\n\n        # Determine endpoint category\n        category = \"default\"\n        if \"\u002Fsearch\" in endpoint:\n            category = \"search\"\n        elif \"\u002Fexport\" in endpoint:\n            category = \"export\"\n\n        max_requests, window = get_rate_limit_for_request(user_tier, category)\n        key = f\"tiered:{user_id or environ.get('REMOTE_ADDR')}:{category}\"\n\n        allowed, current, limit, retry_after = self.limiter.is_allowed(\n            key, max_requests, window)\n\n        if not allowed:\n            status = \"429 Too Many Requests\"\n            headers = [\n                (\"Content-Type\", \"application\u002Fjson\"),\n                (\"Retry-After\", str(retry_after)),\n                (\"X-RateLimit-Limit\", str(limit)),\n                (\"X-RateLimit-Remaining\", \"0\"),\n            ]\n            start_response(status, headers)\n            body = f'{{\"error\":\"rate_limit_exceeded\",\"retry_after\":{retry_after},\"tier\":\"{user_tier.value}\"}}'\n            return [body.encode()]\n\n        return self.app(environ, start_response)\n```\n\n### Step 5: Distributed Rate Limiting for Microservices\n\n```python\n# Centralized rate limiting service using Redis Cluster\nimport redis\nfrom redis.cluster import RedisCluster\n\nclass DistributedRateLimiter:\n    \"\"\"Rate limiter for microservice architectures using Redis Cluster.\"\"\"\n\n    def __init__(self):\n        self.redis = RedisCluster(\n            startup_nodes=[\n                {\"host\": \"redis-node-1\", \"port\": 6379},\n                {\"host\": \"redis-node-2\", \"port\": 6379},\n                {\"host\": \"redis-node-3\", \"port\": 6379},\n            ],\n            decode_responses=True\n        )\n\n    def check_and_increment(self, service_name, user_id, endpoint,\n                             max_requests, window_seconds):\n        \"\"\"Atomic check-and-increment using Redis Lua script.\"\"\"\n        key = f\"rl:{{{service_name}}}:{user_id}:{endpoint}\"\n\n        # Lua script ensures atomicity across the check and increment\n        lua_script = \"\"\"\n        local key = KEYS[1]\n        local max_requests = tonumber(ARGV[1])\n        local window = tonumber(ARGV[2])\n        local now = tonumber(ARGV[3])\n        local window_start = now - window\n\n        -- Remove old entries\n        redis.call('zremrangebyscore', key, '-inf', window_start)\n\n        -- Count current entries\n        local count = redis.call('zcard', key)\n\n        if count >= max_requests then\n            -- Get oldest entry for retry-after calculation\n            local oldest = redis.call('zrange', key, 0, 0, 'WITHSCORES')\n            local retry_after = 0\n            if #oldest > 0 then\n                retry_after = math.ceil(tonumber(oldest[2]) + window - now)\n            end\n            return {0, count, retry_after}\n        end\n\n        -- Add new entry\n        redis.call('zadd', key, now, now .. ':' .. math.random(100000))\n        redis.call('expire', key, window + 1)\n\n        return {1, count + 1, 0}\n        \"\"\"\n\n        result = self.redis.eval(lua_script, 1, key,\n                                  max_requests, window_seconds, time.time())\n        return {\n            \"allowed\": bool(result[0]),\n            \"current\": int(result[1]),\n            \"retry_after\": int(result[2]),\n        }\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| **Sliding Window** | Rate limiting algorithm that tracks requests in a rolling time window, providing smoother rate enforcement than fixed windows |\n| **Token Bucket** | Algorithm where tokens are added at a fixed rate and consumed per request, allowing controlled bursts up to the bucket capacity |\n| **Fixed Window** | Simplest rate limiting where requests are counted per fixed time window (e.g., per minute), susceptible to burst at window boundaries |\n| **429 Too Many Requests** | HTTP status code indicating the client has exceeded the rate limit, accompanied by Retry-After header |\n| **Retry-After Header** | HTTP response header telling the client how many seconds to wait before retrying, essential for well-behaved API clients |\n| **Distributed Rate Limiting** | Rate limiting across multiple server instances using shared state (Redis, Memcached) to maintain accurate global counters |\n\n## Tools & Systems\n\n- **Redis**: In-memory data store used for distributed rate limit counters with atomic operations via Lua scripts\n- **Kong Rate Limiting Plugin**: API gateway plugin supporting fixed-window and sliding-window rate limiting with Redis backend\n- **express-rate-limit**: Express.js middleware for simple rate limiting with Redis, Memcached, or in-memory stores\n- **Flask-Limiter**: Flask extension for rate limiting with support for multiple backends and configurable limits per endpoint\n- **Envoy Rate Limit Service**: Centralized rate limiting service for Envoy-based service mesh architectures\n\n## Common Scenarios\n\n### Scenario: Implementing Rate Limiting for a Public API\n\n**Context**: A company launches a public API with free, premium, and enterprise tiers. The API must protect against abuse while providing fair access to paying customers. The API runs on 6 instances behind an AWS ALB.\n\n**Approach**:\n1. Deploy Redis Cluster (3 nodes) for distributed rate limit state\n2. Implement sliding window rate limiter using Redis sorted sets with Lua scripts for atomicity\n3. Configure per-tier limits: Free (60 req\u002Fmin), Premium (300 req\u002Fmin), Enterprise (1000 req\u002Fmin)\n4. Add stricter limits on authentication endpoints (5 req\u002Fmin per IP) regardless of tier\n5. Implement resource-intensive endpoint limits (search: 10 req\u002Fmin free, export: 5 req\u002Fhour)\n6. Set rate limit response headers on every response (X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset)\n7. Return 429 with Retry-After header and JSON error body when limits are exceeded\n8. Set up Prometheus metrics for rate limit hits and CloudWatch alarms for unusual patterns\n\n**Pitfalls**:\n- Using in-memory rate limiting without shared state across instances, allowing limit bypass by hitting different servers\n- Not implementing rate limiting on authentication endpoints separately from general API limits\n- Using fixed windows that allow burst at window boundaries (2x the limit in a short period)\n- Not including rate limit headers on successful responses, giving clients no visibility into their quota\n- Trusting X-Forwarded-For for IP identification without validating it against the load balancer\n\n## Output Format\n\n```\n## Rate Limiting Implementation Report\n\n**API**: Public API v2\n**Algorithm**: Sliding Window (Redis Sorted Sets)\n**Backend**: Redis Cluster (3 nodes)\n**Deployment**: 6 API instances behind AWS ALB\n\n### Rate Limit Configuration\n\n| Tier | Default | Search | Export | Auth (per IP) |\n|------|---------|--------|--------|---------------|\n| Free | 60\u002Fmin | 10\u002Fmin | 5\u002Fhour | 5\u002Fmin |\n| Premium | 300\u002Fmin | 50\u002Fmin | 20\u002Fhour | 5\u002Fmin |\n| Enterprise | 1000\u002Fmin | 200\u002Fmin | 100\u002Fhour | 10\u002Fmin |\n\n### Validation Results (k6 load test)\n\n- Free tier: Rate limited at 61st request (correct)\n- Premium tier: Rate limited at 301st request (correct)\n- Cross-instance: Rate limiting consistent across all 6 instances\n- Redis failover: Rate limiting degrades gracefully (allows traffic) when Redis is unreachable\n- Retry-After header: Accurate within 1 second of actual reset time\n- Response overhead: \u003C 2ms added latency per request for rate limit check\n```\n","# Implementing API Rate Limiting and Throttling\n\n## When to Use\n\n- Protecting authentication endpoints against brute force and credential stuffing attacks\n- Preventing API abuse and resource exhaustion from automated scripts and bots\n- Implementing fair usage quotas for different API consumer tiers (free, premium, enterprise)\n- Defending against denial-of-service attacks at the application layer\n- Meeting compliance requirements that mandate API abuse prevention controls\n\n**Do not use** rate limiting as the sole defense against attacks. Combine with authentication, authorization, and WAF rules.\n\n## Prerequisites\n\n- Redis 6.0+ for distributed rate limit counters (or in-memory for single-instance deployments)\n- API framework (Express.js, FastAPI, Spring Boot, or Django REST Framework)\n- Monitoring system for rate limit metrics (Prometheus, CloudWatch, Datadog)\n- Understanding of the API's normal traffic patterns and peak usage\n- Load testing tool (k6, Gatling, or Locust) for validating rate limit behavior\n\n## Workflow\n\n### Step 1: Rate Limiting Strategy Design\n\nDefine rate limits per endpoint category and user tier:\n\n```python\n# Rate limit configuration\nRATE_LIMITS = {\n    # Authentication endpoints (most restrictive)\n    \"auth\": {\n        \"login\": {\"requests\": 5, \"window_seconds\": 60, \"by\": \"ip\"},\n        \"register\": {\"requests\": 3, \"window_seconds\": 300, \"by\": \"ip\"},\n        \"forgot_password\": {\"requests\": 3, \"window_seconds\": 3600, \"by\": \"ip\"},\n        \"verify_mfa\": {\"requests\": 5, \"window_seconds\": 300, \"by\": \"user\"},\n    },\n    # Standard API endpoints\n    \"api\": {\n        \"free\": {\"requests\": 60, \"window_seconds\": 60, \"by\": \"user\"},\n        \"premium\": {\"requests\": 300, \"window_seconds\": 60, \"by\": \"user\"},\n        \"enterprise\": {\"requests\": 1000, \"window_seconds\": 60, \"by\": \"user\"},\n    },\n    # Resource-intensive endpoints\n    \"expensive\": {\n        \"search\": {\"requests\": 10, \"window_seconds\": 60, \"by\": \"user\"},\n        \"export\": {\"requests\": 5, \"window_seconds\": 3600, \"by\": \"user\"},\n        \"bulk_import\": {\"requests\": 2, \"window_seconds\": 3600, \"by\": \"user\"},\n    },\n    # Global limits\n    \"global\": {\n        \"per_ip\": {\"requests\": 1000, \"window_seconds\": 60, \"by\": \"ip\"},\n        \"per_user\": {\"requests\": 5000, \"window_seconds\": 3600, \"by\": \"user\"},\n    },\n}\n```\n\n### Step 2: Sliding Window Rate Limiter (Redis)\n\n```python\nimport redis\nimport time\nimport hashlib\nfrom functools import wraps\nfrom flask import Flask, request, jsonify, g\n\napp = Flask(__name__)\nredis_client = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)\n\nclass SlidingWindowRateLimiter:\n    \"\"\"Sliding window rate limiter using Redis sorted sets.\"\"\"\n\n    def __init__(self, redis_conn):\n        self.redis = redis_conn\n\n    def is_allowed(self, key, max_requests, window_seconds):\n        \"\"\"Check if request is allowed and record it.\"\"\"\n        now = time.time()\n        window_start = now - window_seconds\n        pipe = self.redis.pipeline()\n\n        # Remove expired entries\n        pipe.zremrangebyscore(key, 0, window_start)\n        # Count requests in current window\n        pipe.zcard(key)\n        # Add current request\n        pipe.zadd(key, {f\"{now}:{hashlib.md5(str(now).encode()).hexdigest()[:8]}\": now})\n        # Set TTL on the key\n        pipe.expire(key, window_seconds + 1)\n\n        results = pipe.execute()\n        current_count = results[1]\n\n        if current_count >= max_requests:\n            # Calculate retry-after\n            oldest = self.redis.zrange(key, 0, 0, withscores=True)\n            if oldest:\n                retry_after = int(oldest[0][1] + window_seconds - now) + 1\n            else:\n                retry_after = window_seconds\n            return False, current_count, max_requests, retry_after\n\n        return True, current_count + 1, max_requests, 0\n\nrate_limiter = SlidingWindowRateLimiter(redis_client)\n\ndef rate_limit(max_requests, window_seconds, key_func=None):\n    \"\"\"Decorator for rate limiting API endpoints.\"\"\"\n    def decorator(f):\n        @wraps(f)\n        def wrapped(*args, **kwargs):\n            # Determine the rate limit key\n            if key_func:\n                identifier = key_func()\n            elif hasattr(g, 'user_id'):\n                identifier = f\"user:{g.user_id}\"\n            else:\n                identifier = f\"ip:{request.remote_addr}\"\n\n            key = f\"ratelimit:{request.endpoint}:{identifier}\"\n            allowed, current, limit, retry_after = rate_limiter.is_allowed(\n                key, max_requests, window_seconds)\n\n            # Always set rate limit headers\n            headers = {\n                \"X-RateLimit-Limit\": str(limit),\n                \"X-RateLimit-Remaining\": str(max(0, limit - current)),\n                \"X-RateLimit-Reset\": str(int(time.time()) + window_seconds),\n            }\n\n            if not allowed:\n                headers[\"Retry-After\"] = str(retry_after)\n                response = jsonify({\n                    \"error\": \"rate_limit_exceeded\",\n                    \"message\": \"Too many requests. Please try again later.\",\n                    \"retry_after\": retry_after\n                })\n                response.status_code = 429\n                for h, v in headers.items():\n                    response.headers[h] = v\n                return response\n\n            response = f(*args, **kwargs)\n            for h, v in headers.items():\n                response.headers[h] = v\n            return response\n        return wrapped\n    return decorator\n\n# Apply rate limiting to endpoints\n@app.route('\u002Fapi\u002Fv1\u002Fauth\u002Flogin', methods=['POST'])\n@rate_limit(max_requests=5, window_seconds=60,\n            key_func=lambda: f\"ip:{request.remote_addr}\")\ndef login():\n    # Login logic\n    return jsonify({\"message\": \"Login successful\"})\n\n@app.route('\u002Fapi\u002Fv1\u002Fusers\u002Fme', methods=['GET'])\n@rate_limit(max_requests=60, window_seconds=60)\ndef get_profile():\n    # Profile logic\n    return jsonify({\"user\": \"data\"})\n\n@app.route('\u002Fapi\u002Fv1\u002Fsearch', methods=['GET'])\n@rate_limit(max_requests=10, window_seconds=60)\ndef search():\n    # Search logic\n    return jsonify({\"results\": []})\n```\n\n### Step 3: Token Bucket Rate Limiter\n\n```python\nimport redis\nimport time\n\nclass TokenBucketRateLimiter:\n    \"\"\"Token bucket rate limiter allowing burst traffic within limits.\"\"\"\n\n    def __init__(self, redis_conn):\n        self.redis = redis_conn\n\n    def is_allowed(self, key, max_tokens, refill_rate, refill_interval=1):\n        \"\"\"\n        Token bucket algorithm:\n        - max_tokens: Maximum burst capacity\n        - refill_rate: Tokens added per refill_interval\n        - refill_interval: Seconds between refills\n        \"\"\"\n        now = time.time()\n        bucket_key = f\"tb:{key}\"\n\n        # Lua script for atomic token bucket operation\n        lua_script = \"\"\"\n        local key = KEYS[1]\n        local max_tokens = tonumber(ARGV[1])\n        local refill_rate = tonumber(ARGV[2])\n        local refill_interval = tonumber(ARGV[3])\n        local now = tonumber(ARGV[4])\n\n        local bucket = redis.call('hmget', key, 'tokens', 'last_refill')\n        local tokens = tonumber(bucket[1])\n        local last_refill = tonumber(bucket[2])\n\n        if tokens == nil then\n            tokens = max_tokens\n            last_refill = now\n        end\n\n        -- Refill tokens\n        local elapsed = now - last_refill\n        local refills = math.floor(elapsed \u002F refill_interval)\n        if refills > 0 then\n            tokens = math.min(max_tokens, tokens + (refills * refill_rate))\n            last_refill = last_refill + (refills * refill_interval)\n        end\n\n        local allowed = 0\n        if tokens >= 1 then\n            tokens = tokens - 1\n            allowed = 1\n        end\n\n        redis.call('hmset', key, 'tokens', tokens, 'last_refill', last_refill)\n        redis.call('expire', key, math.ceil(max_tokens \u002F refill_rate * refill_interval) + 10)\n\n        return {allowed, tokens, max_tokens}\n        \"\"\"\n\n        result = self.redis.eval(lua_script, 1, bucket_key,\n                                  max_tokens, refill_rate, refill_interval, now)\n        allowed = bool(result[0])\n        remaining = int(result[1])\n        limit = int(result[2])\n\n        return allowed, remaining, limit\n```\n\n### Step 4: Tiered Rate Limiting with User Plans\n\n```python\nfrom enum import Enum\n\nclass UserTier(Enum):\n    FREE = \"free\"\n    PREMIUM = \"premium\"\n    ENTERPRISE = \"enterprise\"\n\nTIER_LIMITS = {\n    UserTier.FREE: {\n        \"default\": (60, 60),          # 60 req\u002Fmin\n        \"search\": (10, 60),           # 10 req\u002Fmin\n        \"export\": (5, 3600),          # 5 req\u002Fhour\n        \"daily_total\": (1000, 86400), # 1000 req\u002Fday\n    },\n    UserTier.PREMIUM: {\n        \"default\": (300, 60),\n        \"search\": (50, 60),\n        \"export\": (20, 3600),\n        \"daily_total\": (10000, 86400),\n    },\n    UserTier.ENTERPRISE: {\n        \"default\": (1000, 60),\n        \"search\": (200, 60),\n        \"export\": (100, 3600),\n        \"daily_total\": (100000, 86400),\n    },\n}\n\ndef get_rate_limit_for_request(user_tier, endpoint_category=\"default\"):\n    \"\"\"Get rate limit configuration based on user tier and endpoint.\"\"\"\n    tier_config = TIER_LIMITS.get(user_tier, TIER_LIMITS[UserTier.FREE])\n    limit_config = tier_config.get(endpoint_category, tier_config[\"default\"])\n    return limit_config  # (max_requests, window_seconds)\n\nclass TieredRateLimitMiddleware:\n    \"\"\"Middleware that applies rate limits based on user subscription tier.\"\"\"\n\n    def __init__(self, app, redis_conn):\n        self.app = app\n        self.limiter = SlidingWindowRateLimiter(redis_conn)\n\n    def __call__(self, environ, start_response):\n        # Extract user info from request\n        user_id = environ.get(\"HTTP_X_USER_ID\")\n        user_tier = UserTier(environ.get(\"HTTP_X_USER_TIER\", \"free\"))\n        endpoint = environ.get(\"PATH_INFO\", \"\u002F\")\n\n        # Determine endpoint category\n        category = \"default\"\n        if \"\u002Fsearch\" in endpoint:\n            category = \"search\"\n        elif \"\u002Fexport\" in endpoint:\n            category = \"export\"\n\n        max_requests, window = get_rate_limit_for_request(user_tier, category)\n        key = f\"tiered:{user_id or environ.get('REMOTE_ADDR')}:{category}\"\n\n        allowed, current, limit, retry_after = self.limiter.is_allowed(\n            key, max_requests, window)\n\n        if not allowed:\n            status = \"429 Too Many Requests\"\n            headers = [\n                (\"Content-Type\", \"application\u002Fjson\"),\n                (\"Retry-After\", str(retry_after)),\n                (\"X-RateLimit-Limit\", str(limit)),\n                (\"X-RateLimit-Remaining\", \"0\"),\n            ]\n            start_response(status, headers)\n            body = f'{{\"error\":\"rate_limit_exceeded\",\"retry_after\":{retry_after},\"tier\":\"{user_tier.value}\"}}'\n            return [body.encode()]\n\n        return self.app(environ, start_response)\n```\n\n### Step 5: Distributed Rate Limiting for Microservices\n\n```python\n# Centralized rate limiting service using Redis Cluster\nimport redis\nfrom redis.cluster import RedisCluster\n\nclass DistributedRateLimiter:\n    \"\"\"Rate limiter for microservice architectures using Redis Cluster.\"\"\"\n\n    def __init__(self):\n        self.redis = RedisCluster(\n            startup_nodes=[\n                {\"host\": \"redis-node-1\", \"port\": 6379},\n                {\"host\": \"redis-node-2\", \"port\": 6379},\n                {\"host\": \"redis-node-3\", \"port\": 6379},\n            ],\n            decode_responses=True\n        )\n\n    def check_and_increment(self, service_name, user_id, endpoint,\n                             max_requests, window_seconds):\n        \"\"\"Atomic check-and-increment using Redis Lua script.\"\"\"\n        key = f\"rl:{{{service_name}}}:{user_id}:{endpoint}\"\n\n        # Lua script ensures atomicity across the check and increment\n        lua_script = \"\"\"\n        local key = KEYS[1]\n        local max_requests = tonumber(ARGV[1])\n        local window = tonumber(ARGV[2])\n        local now = tonumber(ARGV[3])\n        local window_start = now - window\n\n        -- Remove old entries\n        redis.call('zremrangebyscore', key, '-inf', window_start)\n\n        -- Count current entries\n        local count = redis.call('zcard', key)\n\n        if count >= max_requests then\n            -- Get oldest entry for retry-after calculation\n            local oldest = redis.call('zrange', key, 0, 0, 'WITHSCORES')\n            local retry_after = 0\n            if #oldest > 0 then\n                retry_after = math.ceil(tonumber(oldest[2]) + window - now)\n            end\n            return {0, count, retry_after}\n        end\n\n        -- Add new entry\n        redis.call('zadd', key, now, now .. ':' .. math.random(100000))\n        redis.call('expire', key, window + 1)\n\n        return {1, count + 1, 0}\n        \"\"\"\n\n        result = self.redis.eval(lua_script, 1, key,\n                                  max_requests, window_seconds, time.time())\n        return {\n            \"allowed\": bool(result[0]),\n            \"current\": int(result[1]),\n            \"retry_after\": int(result[2]),\n        }\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| **Sliding Window** | Rate limiting algorithm that tracks requests in a rolling time window, providing smoother rate enforcement than fixed windows |\n| **Token Bucket** | Algorithm where tokens are added at a fixed rate and consumed per request, allowing controlled bursts up to the bucket capacity |\n| **Fixed Window** | Simplest rate limiting where requests are counted per fixed time window (e.g., per minute), susceptible to burst at window boundaries |\n| **429 Too Many Requests** | HTTP status code indicating the client has exceeded the rate limit, accompanied by Retry-After header |\n| **Retry-After Header** | HTTP response header telling the client how many seconds to wait before retrying, essential for well-behaved API clients |\n| **Distributed Rate Limiting** | Rate limiting across multiple server instances using shared state (Redis, Memcached) to maintain accurate global counters |\n\n## Tools & Systems\n\n- **Redis**: In-memory data store used for distributed rate limit counters with atomic operations via Lua scripts\n- **Kong Rate Limiting Plugin**: API gateway plugin supporting fixed-window and sliding-window rate limiting with Redis backend\n- **express-rate-limit**: Express.js middleware for simple rate limiting with Redis, Memcached, or in-memory stores\n- **Flask-Limiter**: Flask extension for rate limiting with support for multiple backends and configurable limits per endpoint\n- **Envoy Rate Limit Service**: Centralized rate limiting service for Envoy-based service mesh architectures\n\n## Common Scenarios\n\n### Scenario: Implementing Rate Limiting for a Public API\n\n**Context**: A company launches a public API with free, premium, and enterprise tiers. The API must protect against abuse while providing fair access to paying customers. The API runs on 6 instances behind an AWS ALB.\n\n**Approach**:\n1. Deploy Redis Cluster (3 nodes) for distributed rate limit state\n2. Implement sliding window rate limiter using Redis sorted sets with Lua scripts for atomicity\n3. Configure per-tier limits: Free (60 req\u002Fmin), Premium (300 req\u002Fmin), Enterprise (1000 req\u002Fmin)\n4. Add stricter limits on authentication endpoints (5 req\u002Fmin per IP) regardless of tier\n5. Implement resource-intensive endpoint limits (search: 10 req\u002Fmin free, export: 5 req\u002Fhour)\n6. Set rate limit response headers on every response (X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset)\n7. Return 429 with Retry-After header and JSON error body when limits are exceeded\n8. Set up Prometheus metrics for rate limit hits and CloudWatch alarms for unusual patterns\n\n**Pitfalls**:\n- Using in-memory rate limiting without shared state across instances, allowing limit bypass by hitting different servers\n- Not implementing rate limiting on authentication endpoints separately from general API limits\n- Using fixed windows that allow burst at window boundaries (2x the limit in a short period)\n- Not including rate limit headers on successful responses, giving clients no visibility into their quota\n- Trusting X-Forwarded-For for IP identification without validating it against the load balancer\n\n## Output Format\n\n```\n## Rate Limiting Implementation Report\n\n**API**: Public API v2\n**Algorithm**: Sliding Window (Redis Sorted Sets)\n**Backend**: Redis Cluster (3 nodes)\n**Deployment**: 6 API instances behind AWS ALB\n\n### Rate Limit Configuration\n\n| Tier | Default | Search | Export | Auth (per IP) |\n|------|---------|--------|--------|---------------|\n| Free | 60\u002Fmin | 10\u002Fmin | 5\u002Fhour | 5\u002Fmin |\n| Premium | 300\u002Fmin | 50\u002Fmin | 20\u002Fhour | 5\u002Fmin |\n| Enterprise | 1000\u002Fmin | 200\u002Fmin | 100\u002Fhour | 10\u002Fmin |\n\n### Validation Results (k6 load test)\n\n- Free tier: Rate limited at 61st request (correct)\n- Premium tier: Rate limited at 301st request (correct)\n- Cross-instance: Rate limiting consistent across all 6 instances\n- Redis failover: Rate limiting degrades gracefully (allows traffic) when Redis is unreachable\n- Retry-After header: Accurate within 1 second of actual reset time\n- Response overhead: \u003C 2ms added latency per request for rate limit check\n```\n",{"name":5,"tags":54,"author":55,"domain":48,"license":16,"version":56,"nist_csf":57,"subdomain":41,"description":7,"mitre_attack":62},[41,39,34,42,35,33],"mahipal","1.0.0",[58,59,60,61],"PR.PS-01","ID.RA-01","PR.DS-10","DE.CM-01",[63,64,65,66,67],"T1190","T1059.007","T1552.001","T1003","T1110","main","54a798831d2266a3ca61ce68a7acb80b81160d57","skills\u002Fimplementing-api-rate-limiting-and-throttling",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":9,"skillName":5,"commands":79,"prompt":89,"zipAvailable":90},[80,83,86],{"tool":81,"command":82},"npx","npx skills add mukul975\u002FAnthropic-Cybersecurity-Skills --skill implementing-api-rate-limiting-and-throttling",{"tool":84,"command":85},"bunx","bunx skills add mukul975\u002FAnthropic-Cybersecurity-Skills --skill implementing-api-rate-limiting-and-throttling",{"tool":87,"command":88},"pnpm","pnpm dlx skills add mukul975\u002FAnthropic-Cybersecurity-Skills --skill implementing-api-rate-limiting-and-throttling","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-rate-limiting-and-throttling\u002FSKILL.md",true,[92,97,103],{"path":93,"resourceType":93,"resourceTypeDesc":94,"sizeBytes":95,"sourceHtmlUrl":96},"LICENSE","许可证",11255,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-rate-limiting-and-throttling\u002FLICENSE",{"path":98,"resourceType":99,"resourceTypeDesc":100,"sizeBytes":101,"sourceHtmlUrl":102},"references\u002Fapi-reference.md","REFERENCE","参考文档",1793,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-rate-limiting-and-throttling\u002Freferences\u002Fapi-reference.md",{"path":104,"resourceType":105,"resourceTypeDesc":106,"sizeBytes":107,"sourceHtmlUrl":108},"scripts\u002Fagent.py","SCRIPT","脚本",6314,"https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fimplementing-api-rate-limiting-and-throttling\u002Fscripts\u002Fagent.py",[110,140,169,201,232,264],{"skillNo":111,"name":112,"nameZh":113,"description":114,"descriptionZh":115,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":116,"categories":117,"keywords":122,"publishedAt":49},"01M6AGDM3HJXTKXX15ZZ0ZVCJ3","verifying-build-provenance-with-slsa-sigstore","SLSA 构建来源验证","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.","使用 Sigstore 的 cosign（verify、verify-attestation、verify-blob-attestation）和 slsa-verifier（verify-artifact）验证工件签名和 SLSA 来源（provenance），强制校验 keyless OIDC 构建者身份和源仓库是否符合 SLSA Build 级别。适用于 CI\u002FCD 中部署工件前、消费第三方证明时、建立 SLSA Build L3 管道，或在事件响应或准入控制期间确认来源的场景。","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fverifying-build-provenance-with-slsa-sigstore\u002FSKILL.md",[118,119],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":120,"categoryName":121,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8C32Q37WAMK06SGMFC02VFP","软件供应链安全",[123,124,125,126,40,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":143,"description":144,"descriptionZh":145,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":146,"categories":147,"keywords":152,"publishedAt":49},"01M6AGDGBPWYVZ2F11GFKJ4HZ9","validating-tpm-measured-boot-attestation","TPM 测量启动验证","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.","使用 tpm2-tools 验证 TPM 2.0 测量启动（measured boot）的完整性和远程证明：读取 PCR（tpm2_pcrread）、重放启动事件日志、生成并检查签名报价（tpm2_quote\u002Ftpm2_checkquote），以及将机密封印（seal）到 PCR 策略。适用于确认系统已启动可信固件\u002F内核以实现零信任（Zero Trust）设备状态、通过 PCR 漂移检测启动链篡改，或构建黄金值基线用于机群（fleet）证明。","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fvalidating-tpm-measured-boot-attestation\u002FSKILL.md",[148,149],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":150,"categoryName":151,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8C89JJEXGGRGHS6XVXDA46K","终端安全加固",[153,136,154,155,40,156,48,46,157,158,159,160,161,162,163,164,165,166,167,168],"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":170,"name":171,"nameZh":172,"description":173,"descriptionZh":174,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":175,"categories":176,"keywords":183,"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.","通过加密哈希验证、自动化恢复测试、损坏检测和可恢复性检查来验证备份完整性，确认备份对于灾难恢复和勒索软件响应是可靠的。适用于在依赖备份进行恢复之前、构建备份后验证管道、审计备份基础设施以满足合规要求，或检查不可变\u002Fair-gapped（气隙）备份是否存在静默损坏或篡改的场景。","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Fvalidating-backup-integrity-for-recovery\u002FSKILL.md",[177,180],{"categoryNo":178,"categoryName":179,"taxonomyType":23,"taxonomyTypeDesc":24},"01M8BQGD4WETX0HM3SM9QKQ15B","SRE 工程师",{"categoryNo":181,"categoryName":182,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BSSTY86MWS6W5GDQWB1ADQ","备份与灾难恢复",[163,184,185,186,187,48,188,189,157,190,191,192,193,194,195,196,197,198,199,200],"backup","recovery","validating backup integrity for recovery","testing","infrastructure","validation","compliance","hash-verification","incident-response","ransomware","cryptocurrency","detection","t1078","t1490","immutable","disaster-recovery","restore-testing",{"skillNo":202,"name":203,"nameZh":204,"description":205,"descriptionZh":206,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":207,"categories":208,"keywords":213,"publishedAt":49},"01M6AGD9GBG2KZ336AE763J3WH","triaging-windows-with-kape","KAPE Windows 取证收集","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.","运行 KAPE（Kroll Artifact Parser and Extractor），通过 Targets 收集目标取证工件（注册表配置单元、$MFT、事件日志、prefetch、浏览器数据），并使用封装 Eric Zimmerman 的 EZ Tools（PECmd、MFTECmd、RECmd）的 Modules 进行解析。适用于事件遏制\u002F分诊早期阶段——此时完整磁盘镜像不切实际，但需要快速获得可采信、可解析的 Windows 工件集，包括大规模远程收集。","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Ftriaging-windows-with-kape\u002FSKILL.md",[209,210],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":211,"categoryName":212,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8C9JZH3GWXPJ6CQG5P7J48Y","数字取证与电子证据分析",[214,215,216,48,217,218,219,220,221,222,223,224,225,226,227,228,160,229,230,231],"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":233,"name":234,"nameZh":235,"description":236,"descriptionZh":237,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":238,"categories":239,"keywords":244,"publishedAt":49},"01M6AGD5PW5J4EVZM958WD74ZQ","triaging-vulnerabilities-with-ssvc-framework","SSVC 漏洞优先级分诊","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.","使用 CISA 的 Stakeholder-Specific Vulnerability Categorization（SSVC，利益相关方特定漏洞分类）决策树对漏洞进行分诊和优先级排序，权衡利用状态（通过 CISA KEV 目录和 FIRST EPSS API）、技术影响、自动化程度和任务普遍性，输出 Track\u002FTrack*\u002FAttend\u002FAct 决策。适用于对漏洞扫描结果（OpenVAS、Nessus、Qualys）进行优先级排序以制定修复计划，而不局限于原始 CVSS 分数的场景。","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Ftriaging-vulnerabilities-with-ssvc-framework\u002FSKILL.md",[240,243],{"categoryNo":241,"categoryName":242,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BQV98CYQ7TEW2D1MRQ00TE","安全公告与漏洞管理",{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},[245,246,247,48,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263],"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":265,"name":266,"nameZh":267,"description":268,"descriptionZh":269,"repositoryFullName":9,"ownerLogin":10,"ownerAvatarUrl":11,"ownerAccountNo":12,"ownerDisplayName":13,"repositoryNo":14,"starsCount":15,"licenseSpdxId":16,"licenseFileUrl":17,"sourceHtmlUrl":270,"categories":271,"keywords":276,"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.","使用 NIST SP 800-61r3 和 SANS PICERL 框架对安全事件进行初步分诊，分类事件类型、按业务影响分配优先级，并路由到相应的响应团队。适用于 SIEM\u002FEDR 告警需要人工分类、并发告警必须确定优先级，或用户报告或威胁情报 IOC 匹配需要初步事件分类的场景。","https:\u002F\u002Fgithub.com\u002Fmukul975\u002FAnthropic-Cybersecurity-Skills\u002Fblob\u002Fmain\u002Fskills\u002Ftriaging-security-incident\u002FSKILL.md",[272,273],{"categoryNo":21,"categoryName":22,"taxonomyType":23,"taxonomyTypeDesc":24},{"categoryNo":274,"categoryName":275,"taxonomyType":28,"taxonomyTypeDesc":29},"01M8BTHYSJPJ500X64JJ5CH06D","安全事件响应与威胁狩猎",[40,277,48,278,279,280,281,282,283,284,285,196,286,197,287,288,289,290,291,292],"triaging security incident","siem","file","ioc","soc","NIST-800-61","NIST","severity","edr","execution","analysis","classification","severity-classification","incident-triage","SANS-PICERL","SOC-operations"]