[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7B6Z68ZSWTFXXF0YMPQVG8N":3,"skill-same:01M7B6Z68ZSWTFXXF0YMPQVG8N":88},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":15,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":52,"commitSha":53,"skillDirectory":54,"forksCount":13,"repositoryHtmlUrl":55,"repositoryHomepageUrl":6,"ownerHtmlUrl":56,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":57,"install":58,"resources":71},"01M7B6Z68ZSWTFXXF0YMPQVG8N","implementing-api-key-security-controls",null,"Implements secure API key generation with sufficient entropy, server-side hashing (SHA-256\u002Fbcrypt) instead of plaintext storage, per-key scoping to endpoints\u002FIPs\u002Frate limits, zero-downtime rotation, and automated leak monitoring across GitHub repos, logs, and client-side code. Use when designing API key formats, building key rotation or revocation workflows, or protecting server-to-server API credentials from leakage, brute force, and abuse.","vikasvardhanv\u002Fjerry_skills","vikasvardhanv","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99010657?v=4","01M7B2B0VN78W7529RQX5BR6DZ","01M7B2B0WDNTXJHRK3QNPNWRP6",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\u002Fimplementing-api-key-security-controls\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\u002Fimplementing-api-key-security-controls\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: implementing-api-key-security-controls\ndescription: 'Implements secure API key generation with sufficient entropy, server-side\n  hashing (SHA-256\u002Fbcrypt) instead of plaintext storage, per-key scoping to endpoints\u002FIPs\u002Frate\n  limits, zero-downtime rotation, and automated leak monitoring across GitHub repos,\n  logs, and client-side code. Use when designing API key formats, building key rotation\n  or revocation workflows, or protecting server-to-server API credentials from leakage,\n  brute force, and abuse.'\ndomain: cybersecurity\nsubdomain: api-security\ntags:\n- api-security\n- api-keys\n- credential-management\n- key-rotation\n- secret-management\nversion: 1.0.0\nauthor: mahipal\nlicense: Apache-2.0\nnist_ai_rmf:\n- MEASURE-2.7\n- MAP-5.1\n- MANAGE-2.4\natlas_techniques:\n- AML.T0070\n- AML.T0066\n- AML.T0082\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 Key Security Controls\n\n## When to Use\n\n- Designing secure API key generation with sufficient entropy and identifiable prefixes for leak detection\n- Implementing server-side API key hashing (never storing keys in plaintext) with SHA-256 or bcrypt\n- Building key rotation workflows that allow zero-downtime key replacement for API consumers\n- Configuring per-key scoping to limit each API key to specific endpoints, IP ranges, and rate limits\n- Setting up automated monitoring for API key leakage in GitHub repos, logs, and client-side code\n\n**Do not use** API keys as the sole authentication mechanism for user-facing applications. API keys are best suited for server-to-server communication and developer access.\n\n## Prerequisites\n\n- Secure random number generator (os.urandom, secrets module) for key generation\n- Database with proper encryption at rest for storing hashed API keys\n- Redis or similar store for key-to-metadata caching and rate limiting\n- Secret scanning tools (GitHub secret scanning, truffleHog, gitleaks)\n- Monitoring and alerting infrastructure for key usage anomalies\n\n## Workflow\n\n### Step 1: Secure API Key Generation\n\n```python\nimport secrets\nimport hashlib\nimport hmac\nimport time\nimport json\nfrom datetime import datetime, timedelta\n\nclass APIKeyManager:\n    \"\"\"Manages secure API key lifecycle: generation, storage, validation, rotation.\"\"\"\n\n    # Key format: prefix_base64random (e.g., sk_live_a1b2c3d4e5f6...)\n    # Prefix identifies the key type and environment for leak detection\n    KEY_PREFIXES = {\n        \"live_secret\": \"sk_live_\",\n        \"test_secret\": \"sk_test_\",\n        \"live_public\": \"pk_live_\",\n        \"test_public\": \"pk_test_\",\n    }\n\n    def __init__(self, db_connection, redis_connection):\n        self.db = db_connection\n        self.redis = redis_connection\n\n    def generate_key(self, key_type=\"live_secret\", owner_id=None, scopes=None,\n                     rate_limit=None, ip_allowlist=None, expires_days=365):\n        \"\"\"Generate a new API key with metadata.\"\"\"\n        prefix = self.KEY_PREFIXES.get(key_type, \"sk_live_\")\n\n        # Generate 32 bytes (256 bits) of randomness\n        random_bytes = secrets.token_bytes(32)\n        key_body = secrets.token_urlsafe(32)  # Base64url-encoded\n\n        # Full API key that the client receives (shown only once)\n        full_key = f\"{prefix}{key_body}\"\n\n        # Hash the key for storage (never store the raw key)\n        key_hash = hashlib.sha256(full_key.encode()).hexdigest()\n\n        # Create a short key ID for reference (first 8 chars)\n        key_id = f\"{prefix}{key_body[:8]}...\"\n\n        # Store the hashed key with metadata\n        key_metadata = {\n            \"key_hash\": key_hash,\n            \"key_id\": key_id,\n            \"key_type\": key_type,\n            \"owner_id\": owner_id,\n            \"scopes\": scopes or [\"read\"],\n            \"rate_limit\": rate_limit or {\"requests\": 1000, \"window\": 3600},\n            \"ip_allowlist\": ip_allowlist or [],\n            \"created_at\": datetime.utcnow().isoformat(),\n            \"expires_at\": (datetime.utcnow() + timedelta(days=expires_days)).isoformat(),\n            \"last_used\": None,\n            \"is_active\": True,\n            \"usage_count\": 0,\n        }\n\n        # Store in database\n        self.db.execute(\n            \"INSERT INTO api_keys (key_hash, key_id, metadata) VALUES (?, ?, ?)\",\n            (key_hash, key_id, json.dumps(key_metadata))\n        )\n\n        # Cache in Redis for fast validation\n        self.redis.setex(\n            f\"apikey:{key_hash}\",\n            86400,  # 24-hour cache TTL\n            json.dumps(key_metadata)\n        )\n\n        return {\n            \"api_key\": full_key,       # Show to user ONCE\n            \"key_id\": key_id,          # For reference\u002Fmanagement\n            \"scopes\": key_metadata[\"scopes\"],\n            \"expires_at\": key_metadata[\"expires_at\"],\n        }\n\n    def validate_key(self, api_key):\n        \"\"\"Validate an API key and return its metadata.\"\"\"\n        key_hash = hashlib.sha256(api_key.encode()).hexdigest()\n\n        # Check Redis cache first\n        cached = self.redis.get(f\"apikey:{key_hash}\")\n        if cached:\n            metadata = json.loads(cached)\n        else:\n            # Fall back to database\n            row = self.db.execute(\n                \"SELECT metadata FROM api_keys WHERE key_hash = ?\",\n                (key_hash,)\n            ).fetchone()\n            if not row:\n                return None, \"invalid_key\"\n            metadata = json.loads(row[0])\n            # Refresh cache\n            self.redis.setex(f\"apikey:{key_hash}\", 86400, row[0])\n\n        # Validation checks\n        if not metadata.get(\"is_active\"):\n            return None, \"key_revoked\"\n\n        if metadata.get(\"expires_at\"):\n            if datetime.fromisoformat(metadata[\"expires_at\"]) \u003C datetime.utcnow():\n                return None, \"key_expired\"\n\n        # Update last used\n        metadata[\"last_used\"] = datetime.utcnow().isoformat()\n        metadata[\"usage_count\"] = metadata.get(\"usage_count\", 0) + 1\n        self.redis.setex(f\"apikey:{key_hash}\", 86400, json.dumps(metadata))\n\n        return metadata, \"valid\"\n\n    def revoke_key(self, key_id):\n        \"\"\"Immediately revoke an API key.\"\"\"\n        row = self.db.execute(\n            \"SELECT key_hash, metadata FROM api_keys WHERE key_id = ?\",\n            (key_id,)\n        ).fetchone()\n        if row:\n            key_hash = row[0]\n            metadata = json.loads(row[1])\n            metadata[\"is_active\"] = False\n            metadata[\"revoked_at\"] = datetime.utcnow().isoformat()\n\n            self.db.execute(\n                \"UPDATE api_keys SET metadata = ? WHERE key_id = ?\",\n                (json.dumps(metadata), key_id)\n            )\n            # Invalidate cache immediately\n            self.redis.delete(f\"apikey:{key_hash}\")\n            return True\n        return False\n\n    def rotate_key(self, old_key_id, grace_period_hours=24):\n        \"\"\"Rotate an API key with a grace period where both old and new keys work.\"\"\"\n        old_row = self.db.execute(\n            \"SELECT key_hash, metadata FROM api_keys WHERE key_id = ?\",\n            (old_key_id,)\n        ).fetchone()\n        if not old_row:\n            return None, \"key_not_found\"\n\n        old_metadata = json.loads(old_row[1])\n\n        # Generate new key with same settings\n        new_key_data = self.generate_key(\n            key_type=old_metadata[\"key_type\"],\n            owner_id=old_metadata[\"owner_id\"],\n            scopes=old_metadata[\"scopes\"],\n            rate_limit=old_metadata[\"rate_limit\"],\n            ip_allowlist=old_metadata[\"ip_allowlist\"],\n        )\n\n        # Schedule old key revocation after grace period\n        revoke_at = datetime.utcnow() + timedelta(hours=grace_period_hours)\n        old_metadata[\"scheduled_revocation\"] = revoke_at.isoformat()\n        self.db.execute(\n            \"UPDATE api_keys SET metadata = ? WHERE key_id = ?\",\n            (json.dumps(old_metadata), old_key_id)\n        )\n\n        return {\n            \"new_key\": new_key_data,\n            \"old_key_id\": old_key_id,\n            \"old_key_revokes_at\": revoke_at.isoformat(),\n            \"message\": f\"Old key will be revoked in {grace_period_hours} hours\"\n        }, \"success\"\n```\n\n### Step 2: API Key Validation Middleware\n\n```python\nfrom flask import Flask, request, jsonify, g\nfrom functools import wraps\n\napp = Flask(__name__)\n\ndef require_api_key(required_scopes=None):\n    \"\"\"Middleware to validate API key and check scopes.\"\"\"\n    def decorator(f):\n        @wraps(f)\n        def wrapped(*args, **kwargs):\n            # Extract API key from header\n            api_key = request.headers.get(\"X-API-Key\")\n            if not api_key:\n                # Also check Authorization: Bearer \u003Ckey>\n                auth_header = request.headers.get(\"Authorization\", \"\")\n                if auth_header.startswith(\"Bearer \"):\n                    api_key = auth_header[7:]\n\n            if not api_key:\n                return jsonify({\"error\": \"missing_api_key\"}), 401\n\n            # Validate the key\n            metadata, status = key_manager.validate_key(api_key)\n            if status != \"valid\":\n                return jsonify({\"error\": status}), 401\n\n            # Check IP allowlist\n            if metadata.get(\"ip_allowlist\"):\n                client_ip = request.remote_addr\n                if client_ip not in metadata[\"ip_allowlist\"]:\n                    return jsonify({\"error\": \"ip_not_allowed\"}), 403\n\n            # Check scopes\n            if required_scopes:\n                key_scopes = set(metadata.get(\"scopes\", []))\n                if not key_scopes.intersection(required_scopes):\n                    return jsonify({\"error\": \"insufficient_scope\"}), 403\n\n            # Attach metadata to request context\n            g.api_key_metadata = metadata\n            return f(*args, **kwargs)\n        return wrapped\n    return decorator\n\n@app.route('\u002Fapi\u002Fv1\u002Fdata', methods=['GET'])\n@require_api_key(required_scopes=[\"read\", \"admin\"])\ndef get_data():\n    return jsonify({\"data\": \"sensitive information\"})\n\n@app.route('\u002Fapi\u002Fv1\u002Fdata', methods=['POST'])\n@require_api_key(required_scopes=[\"write\", \"admin\"])\ndef create_data():\n    return jsonify({\"created\": True})\n```\n\n### Step 3: Automated Key Leakage Detection\n\n```bash\n# Scan GitHub repositories for leaked API keys using gitleaks\ngitleaks detect --source=\u002Fpath\u002Fto\u002Frepo --config=gitleaks.toml --report-path=leaks.json\n\n# Custom gitleaks configuration for API key prefix detection\n# gitleaks.toml\ncat \u003C\u003C'EOF'\n[[rules]]\nid = \"company-api-key-live\"\ndescription = \"Company Live API Key\"\nregex = '''sk_live_[A-Za-z0-9_-]{32,}'''\ntags = [\"api-key\", \"live\", \"critical\"]\n\n[[rules]]\nid = \"company-api-key-test\"\ndescription = \"Company Test API Key\"\nregex = '''sk_test_[A-Za-z0-9_-]{32,}'''\ntags = [\"api-key\", \"test\"]\n\n[[rules]]\nid = \"company-public-key\"\ndescription = \"Company Public API Key\"\nregex = '''pk_live_[A-Za-z0-9_-]{32,}'''\ntags = [\"api-key\", \"public\"]\nEOF\n```\n\n```python\n# Automated leaked key revocation\nimport json\n\ndef process_leaked_keys(leaks_file):\n    \"\"\"Automatically revoke API keys detected in public repositories.\"\"\"\n    with open(leaks_file) as f:\n        leaks = json.load(f)\n\n    for leak in leaks:\n        key_match = leak.get(\"match\", \"\")\n        # Extract the key from the match\n        for prefix in [\"sk_live_\", \"sk_test_\", \"pk_live_\"]:\n            if prefix in key_match:\n                start = key_match.index(prefix)\n                potential_key = key_match[start:start+50]  # Max key length\n                # Validate and revoke\n                metadata, status = key_manager.validate_key(potential_key)\n                if status == \"valid\":\n                    key_manager.revoke_key(metadata[\"key_id\"])\n                    print(f\"[REVOKED] Key {metadata['key_id']} leaked in {leak.get('file')}\")\n                    # Notify the key owner\n                    notify_owner(metadata[\"owner_id\"], metadata[\"key_id\"], leak)\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| **API Key** | A secret string used to authenticate API requests, typically passed in headers or query parameters |\n| **Key Hashing** | Storing only the hash (SHA-256) of the API key in the database, never the plaintext key, similar to password hashing |\n| **Key Rotation** | Replacing an API key with a new one while maintaining a grace period where both keys work, ensuring zero-downtime transition |\n| **Key Scoping** | Limiting each API key to specific endpoints, HTTP methods, IP ranges, and rate limits to minimize blast radius |\n| **Key Prefix** | An identifiable prefix (e.g., sk_live_) that enables automated detection of leaked keys in logs, code, and public repositories |\n| **Secret Scanning** | Automated monitoring of repositories, logs, and public sources for exposed API keys and credentials |\n\n## Tools & Systems\n\n- **GitHub Secret Scanning**: Built-in GitHub feature that detects exposed secrets in repositories and alerts key providers\n- **gitleaks**: Open-source tool for detecting secrets in git repositories using customizable regex patterns\n- **truffleHog**: Secret scanning tool that searches entire git history for high-entropy strings and known secret patterns\n- **HashiCorp Vault**: Enterprise secret management system for API key storage, rotation, and dynamic credential generation\n- **AWS Secrets Manager**: Managed secret storage with automatic rotation support for API keys and credentials\n\n## Common Scenarios\n\n### Scenario: API Key Security Program for Developer Platform\n\n**Context**: A developer platform provides public APIs authenticated with API keys. The platform has 10,000+ API consumers generating 50M+ requests per day. Keys are frequently leaked in public GitHub repositories.\n\n**Approach**:\n1. Implement prefixed API keys (sk_live_, sk_test_) with 256-bit entropy for leak detection\n2. Store only SHA-256 hashes of keys in the database, cache validated keys in Redis\n3. Implement per-key scoping: each key restricted to specific endpoints, rate limits, and optional IP allowlists\n4. Build key rotation API with 24-hour grace period for seamless transitions\n5. Integrate with GitHub Secret Scanning to automatically detect and revoke leaked keys within minutes\n6. Run gitleaks in CI\u002FCD pipelines to prevent key commits in first place\n7. Implement anomaly detection: alert on keys used from unusual IPs or with abnormal traffic patterns\n8. Add key expiration policy: all keys expire after 365 days with 30-day advance notification\n\n**Pitfalls**:\n- Storing API keys in plaintext in the database (use SHA-256 hashing)\n- Using predictable or low-entropy key generation (use cryptographically secure random generators)\n- Not implementing key prefixes, making it impossible to identify leaked keys in automated scans\n- Allowing API keys in URL query parameters where they leak in logs, browser history, and Referer headers\n- Not implementing rate limiting per key, allowing a single compromised key to abuse the entire API\n\n## Output Format\n\n```\n## API Key Security Implementation Report\n\n**Platform**: Developer API v3\n**Total Active Keys**: 12,450\n**Daily Key Validations**: 52M\n\n### Security Controls\n\n| Control | Implementation | Status |\n|---------|---------------|--------|\n| Key Entropy | 256-bit (secrets.token_urlsafe(32)) | Implemented |\n| Key Format | sk_live_\u002Fsk_test_ prefixed | Implemented |\n| Storage | SHA-256 hashed, Redis cached | Implemented |\n| Scoping | Per-key endpoint\u002FIP\u002Frate limits | Implemented |\n| Rotation | 24-hour grace period API | Implemented |\n| Expiration | 365-day max TTL | Implemented |\n| Leak Detection | GitHub Secret Scanning + gitleaks | Active |\n| Auto-Revocation | Leaked keys revoked within 5 min | Active |\n\n### Key Leakage Stats (Last 30 Days)\n- Keys detected in public repos: 23\n- Average time to revocation: 3.2 minutes\n- Keys detected in CI\u002FCD pre-commit: 7 (prevented)\n```\n","# Implementing API Key Security Controls\n\n## When to Use\n\n- Designing secure API key generation with sufficient entropy and identifiable prefixes for leak detection\n- Implementing server-side API key hashing (never storing keys in plaintext) with SHA-256 or bcrypt\n- Building key rotation workflows that allow zero-downtime key replacement for API consumers\n- Configuring per-key scoping to limit each API key to specific endpoints, IP ranges, and rate limits\n- Setting up automated monitoring for API key leakage in GitHub repos, logs, and client-side code\n\n**Do not use** API keys as the sole authentication mechanism for user-facing applications. API keys are best suited for server-to-server communication and developer access.\n\n## Prerequisites\n\n- Secure random number generator (os.urandom, secrets module) for key generation\n- Database with proper encryption at rest for storing hashed API keys\n- Redis or similar store for key-to-metadata caching and rate limiting\n- Secret scanning tools (GitHub secret scanning, truffleHog, gitleaks)\n- Monitoring and alerting infrastructure for key usage anomalies\n\n## Workflow\n\n### Step 1: Secure API Key Generation\n\n```python\nimport secrets\nimport hashlib\nimport hmac\nimport time\nimport json\nfrom datetime import datetime, timedelta\n\nclass APIKeyManager:\n    \"\"\"Manages secure API key lifecycle: generation, storage, validation, rotation.\"\"\"\n\n    # Key format: prefix_base64random (e.g., sk_live_a1b2c3d4e5f6...)\n    # Prefix identifies the key type and environment for leak detection\n    KEY_PREFIXES = {\n        \"live_secret\": \"sk_live_\",\n        \"test_secret\": \"sk_test_\",\n        \"live_public\": \"pk_live_\",\n        \"test_public\": \"pk_test_\",\n    }\n\n    def __init__(self, db_connection, redis_connection):\n        self.db = db_connection\n        self.redis = redis_connection\n\n    def generate_key(self, key_type=\"live_secret\", owner_id=None, scopes=None,\n                     rate_limit=None, ip_allowlist=None, expires_days=365):\n        \"\"\"Generate a new API key with metadata.\"\"\"\n        prefix = self.KEY_PREFIXES.get(key_type, \"sk_live_\")\n\n        # Generate 32 bytes (256 bits) of randomness\n        random_bytes = secrets.token_bytes(32)\n        key_body = secrets.token_urlsafe(32)  # Base64url-encoded\n\n        # Full API key that the client receives (shown only once)\n        full_key = f\"{prefix}{key_body}\"\n\n        # Hash the key for storage (never store the raw key)\n        key_hash = hashlib.sha256(full_key.encode()).hexdigest()\n\n        # Create a short key ID for reference (first 8 chars)\n        key_id = f\"{prefix}{key_body[:8]}...\"\n\n        # Store the hashed key with metadata\n        key_metadata = {\n            \"key_hash\": key_hash,\n            \"key_id\": key_id,\n            \"key_type\": key_type,\n            \"owner_id\": owner_id,\n            \"scopes\": scopes or [\"read\"],\n            \"rate_limit\": rate_limit or {\"requests\": 1000, \"window\": 3600},\n            \"ip_allowlist\": ip_allowlist or [],\n            \"created_at\": datetime.utcnow().isoformat(),\n            \"expires_at\": (datetime.utcnow() + timedelta(days=expires_days)).isoformat(),\n            \"last_used\": None,\n            \"is_active\": True,\n            \"usage_count\": 0,\n        }\n\n        # Store in database\n        self.db.execute(\n            \"INSERT INTO api_keys (key_hash, key_id, metadata) VALUES (?, ?, ?)\",\n            (key_hash, key_id, json.dumps(key_metadata))\n        )\n\n        # Cache in Redis for fast validation\n        self.redis.setex(\n            f\"apikey:{key_hash}\",\n            86400,  # 24-hour cache TTL\n            json.dumps(key_metadata)\n        )\n\n        return {\n            \"api_key\": full_key,       # Show to user ONCE\n            \"key_id\": key_id,          # For reference\u002Fmanagement\n            \"scopes\": key_metadata[\"scopes\"],\n            \"expires_at\": key_metadata[\"expires_at\"],\n        }\n\n    def validate_key(self, api_key):\n        \"\"\"Validate an API key and return its metadata.\"\"\"\n        key_hash = hashlib.sha256(api_key.encode()).hexdigest()\n\n        # Check Redis cache first\n        cached = self.redis.get(f\"apikey:{key_hash}\")\n        if cached:\n            metadata = json.loads(cached)\n        else:\n            # Fall back to database\n            row = self.db.execute(\n                \"SELECT metadata FROM api_keys WHERE key_hash = ?\",\n                (key_hash,)\n            ).fetchone()\n            if not row:\n                return None, \"invalid_key\"\n            metadata = json.loads(row[0])\n            # Refresh cache\n            self.redis.setex(f\"apikey:{key_hash}\", 86400, row[0])\n\n        # Validation checks\n        if not metadata.get(\"is_active\"):\n            return None, \"key_revoked\"\n\n        if metadata.get(\"expires_at\"):\n            if datetime.fromisoformat(metadata[\"expires_at\"]) \u003C datetime.utcnow():\n                return None, \"key_expired\"\n\n        # Update last used\n        metadata[\"last_used\"] = datetime.utcnow().isoformat()\n        metadata[\"usage_count\"] = metadata.get(\"usage_count\", 0) + 1\n        self.redis.setex(f\"apikey:{key_hash}\", 86400, json.dumps(metadata))\n\n        return metadata, \"valid\"\n\n    def revoke_key(self, key_id):\n        \"\"\"Immediately revoke an API key.\"\"\"\n        row = self.db.execute(\n            \"SELECT key_hash, metadata FROM api_keys WHERE key_id = ?\",\n            (key_id,)\n        ).fetchone()\n        if row:\n            key_hash = row[0]\n            metadata = json.loads(row[1])\n            metadata[\"is_active\"] = False\n            metadata[\"revoked_at\"] = datetime.utcnow().isoformat()\n\n            self.db.execute(\n                \"UPDATE api_keys SET metadata = ? WHERE key_id = ?\",\n                (json.dumps(metadata), key_id)\n            )\n            # Invalidate cache immediately\n            self.redis.delete(f\"apikey:{key_hash}\")\n            return True\n        return False\n\n    def rotate_key(self, old_key_id, grace_period_hours=24):\n        \"\"\"Rotate an API key with a grace period where both old and new keys work.\"\"\"\n        old_row = self.db.execute(\n            \"SELECT key_hash, metadata FROM api_keys WHERE key_id = ?\",\n            (old_key_id,)\n        ).fetchone()\n        if not old_row:\n            return None, \"key_not_found\"\n\n        old_metadata = json.loads(old_row[1])\n\n        # Generate new key with same settings\n        new_key_data = self.generate_key(\n            key_type=old_metadata[\"key_type\"],\n            owner_id=old_metadata[\"owner_id\"],\n            scopes=old_metadata[\"scopes\"],\n            rate_limit=old_metadata[\"rate_limit\"],\n            ip_allowlist=old_metadata[\"ip_allowlist\"],\n        )\n\n        # Schedule old key revocation after grace period\n        revoke_at = datetime.utcnow() + timedelta(hours=grace_period_hours)\n        old_metadata[\"scheduled_revocation\"] = revoke_at.isoformat()\n        self.db.execute(\n            \"UPDATE api_keys SET metadata = ? WHERE key_id = ?\",\n            (json.dumps(old_metadata), old_key_id)\n        )\n\n        return {\n            \"new_key\": new_key_data,\n            \"old_key_id\": old_key_id,\n            \"old_key_revokes_at\": revoke_at.isoformat(),\n            \"message\": f\"Old key will be revoked in {grace_period_hours} hours\"\n        }, \"success\"\n```\n\n### Step 2: API Key Validation Middleware\n\n```python\nfrom flask import Flask, request, jsonify, g\nfrom functools import wraps\n\napp = Flask(__name__)\n\ndef require_api_key(required_scopes=None):\n    \"\"\"Middleware to validate API key and check scopes.\"\"\"\n    def decorator(f):\n        @wraps(f)\n        def wrapped(*args, **kwargs):\n            # Extract API key from header\n            api_key = request.headers.get(\"X-API-Key\")\n            if not api_key:\n                # Also check Authorization: Bearer \u003Ckey>\n                auth_header = request.headers.get(\"Authorization\", \"\")\n                if auth_header.startswith(\"Bearer \"):\n                    api_key = auth_header[7:]\n\n            if not api_key:\n                return jsonify({\"error\": \"missing_api_key\"}), 401\n\n            # Validate the key\n            metadata, status = key_manager.validate_key(api_key)\n            if status != \"valid\":\n                return jsonify({\"error\": status}), 401\n\n            # Check IP allowlist\n            if metadata.get(\"ip_allowlist\"):\n                client_ip = request.remote_addr\n                if client_ip not in metadata[\"ip_allowlist\"]:\n                    return jsonify({\"error\": \"ip_not_allowed\"}), 403\n\n            # Check scopes\n            if required_scopes:\n                key_scopes = set(metadata.get(\"scopes\", []))\n                if not key_scopes.intersection(required_scopes):\n                    return jsonify({\"error\": \"insufficient_scope\"}), 403\n\n            # Attach metadata to request context\n            g.api_key_metadata = metadata\n            return f(*args, **kwargs)\n        return wrapped\n    return decorator\n\n@app.route('\u002Fapi\u002Fv1\u002Fdata', methods=['GET'])\n@require_api_key(required_scopes=[\"read\", \"admin\"])\ndef get_data():\n    return jsonify({\"data\": \"sensitive information\"})\n\n@app.route('\u002Fapi\u002Fv1\u002Fdata', methods=['POST'])\n@require_api_key(required_scopes=[\"write\", \"admin\"])\ndef create_data():\n    return jsonify({\"created\": True})\n```\n\n### Step 3: Automated Key Leakage Detection\n\n```bash\n# Scan GitHub repositories for leaked API keys using gitleaks\ngitleaks detect --source=\u002Fpath\u002Fto\u002Frepo --config=gitleaks.toml --report-path=leaks.json\n\n# Custom gitleaks configuration for API key prefix detection\n# gitleaks.toml\ncat \u003C\u003C'EOF'\n[[rules]]\nid = \"company-api-key-live\"\ndescription = \"Company Live API Key\"\nregex = '''sk_live_[A-Za-z0-9_-]{32,}'''\ntags = [\"api-key\", \"live\", \"critical\"]\n\n[[rules]]\nid = \"company-api-key-test\"\ndescription = \"Company Test API Key\"\nregex = '''sk_test_[A-Za-z0-9_-]{32,}'''\ntags = [\"api-key\", \"test\"]\n\n[[rules]]\nid = \"company-public-key\"\ndescription = \"Company Public API Key\"\nregex = '''pk_live_[A-Za-z0-9_-]{32,}'''\ntags = [\"api-key\", \"public\"]\nEOF\n```\n\n```python\n# Automated leaked key revocation\nimport json\n\ndef process_leaked_keys(leaks_file):\n    \"\"\"Automatically revoke API keys detected in public repositories.\"\"\"\n    with open(leaks_file) as f:\n        leaks = json.load(f)\n\n    for leak in leaks:\n        key_match = leak.get(\"match\", \"\")\n        # Extract the key from the match\n        for prefix in [\"sk_live_\", \"sk_test_\", \"pk_live_\"]:\n            if prefix in key_match:\n                start = key_match.index(prefix)\n                potential_key = key_match[start:start+50]  # Max key length\n                # Validate and revoke\n                metadata, status = key_manager.validate_key(potential_key)\n                if status == \"valid\":\n                    key_manager.revoke_key(metadata[\"key_id\"])\n                    print(f\"[REVOKED] Key {metadata['key_id']} leaked in {leak.get('file')}\")\n                    # Notify the key owner\n                    notify_owner(metadata[\"owner_id\"], metadata[\"key_id\"], leak)\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| **API Key** | A secret string used to authenticate API requests, typically passed in headers or query parameters |\n| **Key Hashing** | Storing only the hash (SHA-256) of the API key in the database, never the plaintext key, similar to password hashing |\n| **Key Rotation** | Replacing an API key with a new one while maintaining a grace period where both keys work, ensuring zero-downtime transition |\n| **Key Scoping** | Limiting each API key to specific endpoints, HTTP methods, IP ranges, and rate limits to minimize blast radius |\n| **Key Prefix** | An identifiable prefix (e.g., sk_live_) that enables automated detection of leaked keys in logs, code, and public repositories |\n| **Secret Scanning** | Automated monitoring of repositories, logs, and public sources for exposed API keys and credentials |\n\n## Tools & Systems\n\n- **GitHub Secret Scanning**: Built-in GitHub feature that detects exposed secrets in repositories and alerts key providers\n- **gitleaks**: Open-source tool for detecting secrets in git repositories using customizable regex patterns\n- **truffleHog**: Secret scanning tool that searches entire git history for high-entropy strings and known secret patterns\n- **HashiCorp Vault**: Enterprise secret management system for API key storage, rotation, and dynamic credential generation\n- **AWS Secrets Manager**: Managed secret storage with automatic rotation support for API keys and credentials\n\n## Common Scenarios\n\n### Scenario: API Key Security Program for Developer Platform\n\n**Context**: A developer platform provides public APIs authenticated with API keys. The platform has 10,000+ API consumers generating 50M+ requests per day. Keys are frequently leaked in public GitHub repositories.\n\n**Approach**:\n1. Implement prefixed API keys (sk_live_, sk_test_) with 256-bit entropy for leak detection\n2. Store only SHA-256 hashes of keys in the database, cache validated keys in Redis\n3. Implement per-key scoping: each key restricted to specific endpoints, rate limits, and optional IP allowlists\n4. Build key rotation API with 24-hour grace period for seamless transitions\n5. Integrate with GitHub Secret Scanning to automatically detect and revoke leaked keys within minutes\n6. Run gitleaks in CI\u002FCD pipelines to prevent key commits in first place\n7. Implement anomaly detection: alert on keys used from unusual IPs or with abnormal traffic patterns\n8. Add key expiration policy: all keys expire after 365 days with 30-day advance notification\n\n**Pitfalls**:\n- Storing API keys in plaintext in the database (use SHA-256 hashing)\n- Using predictable or low-entropy key generation (use cryptographically secure random generators)\n- Not implementing key prefixes, making it impossible to identify leaked keys in automated scans\n- Allowing API keys in URL query parameters where they leak in logs, browser history, and Referer headers\n- Not implementing rate limiting per key, allowing a single compromised key to abuse the entire API\n\n## Output Format\n\n```\n## API Key Security Implementation Report\n\n**Platform**: Developer API v3\n**Total Active Keys**: 12,450\n**Daily Key Validations**: 52M\n\n### Security Controls\n\n| Control | Implementation | Status |\n|---------|---------------|--------|\n| Key Entropy | 256-bit (secrets.token_urlsafe(32)) | Implemented |\n| Key Format | sk_live_\u002Fsk_test_ prefixed | Implemented |\n| Storage | SHA-256 hashed, Redis cached | Implemented |\n| Scoping | Per-key endpoint\u002FIP\u002Frate limits | Implemented |\n| Rotation | 24-hour grace period API | Implemented |\n| Expiration | 365-day max TTL | Implemented |\n| Leak Detection | GitHub Secret Scanning + gitleaks | Active |\n| Auto-Revocation | Leaked keys revoked within 5 min | Active |\n\n### Key Leakage Stats (Last 30 Days)\n- Keys detected in public repos: 23\n- Average time to revocation: 3.2 minutes\n- Keys detected in CI\u002FCD pre-commit: 7 (prevented)\n```\n",{"name":5,"tags":24,"author":30,"domain":31,"license":14,"version":32,"nist_csf":33,"subdomain":25,"description":7,"nist_ai_rmf":38,"mitre_attack":42,"atlas_techniques":48},[25,26,27,28,29],"api-security","api-keys","credential-management","key-rotation","secret-management","mahipal","cybersecurity","1.0.0",[34,35,36,37],"PR.PS-01","ID.RA-01","PR.DS-10","DE.CM-01",[39,40,41],"MEASURE-2.7","MAP-5.1","MANAGE-2.4",[43,44,45,46,47],"T1190","T1059.007","T1552.001","T1003","T1110",[49,50,51],"AML.T0070","AML.T0066","AML.T0082","main","1eb986d0b0ecc180291597e08eb5a58288843536","skills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\u002Fimplementing-api-key-security-controls","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv","2026-08-25 13:16:33",{"source":8,"skillName":5,"commands":59,"prompt":69,"zipAvailable":70},[60,63,66],{"tool":61,"command":62},"npx","npx skills add vikasvardhanv\u002Fjerry_skills --skill implementing-api-key-security-controls",{"tool":64,"command":65},"bunx","bunx skills add vikasvardhanv\u002Fjerry_skills --skill implementing-api-key-security-controls",{"tool":67,"command":68},"pnpm","pnpm dlx skills add vikasvardhanv\u002Fjerry_skills --skill implementing-api-key-security-controls","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\u002Fimplementing-api-key-security-controls\u002FSKILL.md",true,[72,76,82],{"path":73,"resourceType":73,"resourceTypeDesc":74,"sizeBytes":75,"sourceHtmlUrl":15},"LICENSE","许可证",11255,{"path":77,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":80,"sourceHtmlUrl":81},"references\u002Fapi-reference.md","REFERENCE","参考文档",1327,"https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\u002Fimplementing-api-key-security-controls\u002Freferences\u002Fapi-reference.md",{"path":83,"resourceType":84,"resourceTypeDesc":85,"sizeBytes":86,"sourceHtmlUrl":87},"scripts\u002Fagent.py","SCRIPT","脚本",6010,"https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\u002Fimplementing-api-key-security-controls\u002Fscripts\u002Fagent.py",[89,97,104,111,118,125],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":93,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":19},"01M7BESR1CJ3H5SP9XM8KYJZ9W","syllabus","Generates a curated supplementary reading list from any course syllabus using Consensus academic search. Grill-me intake (syllabus input format + course audience + year range) plus a grouping forcing-options checkpoint before any search runs — so the reading list matches the course's level and recency need. Parses the syllabus to extract topics and learning outcomes, searches Consensus for recent peer-reviewed papers per topic, and produces a professionally formatted .docx with clickable Consensus links, plain-language summaries calibrated to audience level, and Bloom-higher-order discussion questions tied to course learning goals. Use when the user uploads a syllabus, course outline, or curriculum document and wants supplementary readings (e.g., 'create a reading list from this syllabus', 'find recent papers for my course') — even casual mentions with a syllabus attached should trigger this skill.","MIT","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fsyllabus\u002Fskills\u002Fsyllabus\u002FSKILL.md",[],[],{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":93,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":19},"01M7BES1YA6R97W7QPMFFM1PED","pulse","Multi-source recency research skill that takes the pulse of any topic across Reddit, Hacker News, the open web, and optionally X\u002FTwitter within a configurable recent window (default 30 days). Forcing intake clarifies topic specificity, angle (trend\u002Fsentiment\u002Fproblems\u002Fopportunities\u002Fcomparison), time window, and platform scope before searching. Returns a synthesized briefing with citations, engagement metrics, and cross-platform pattern analysis. Use when the user requests multi-source recency intelligence on a topic (e.g., 'pulse on [topic]', 'what's happening with [topic]', 'what are people saying about [topic]', 'current conversation about [topic]', 'take the pulse of [topic]', 'trending: [topic]', 'find me info on [topic]'), and for competitor research, trend discovery, tool comparisons, and audience sentiment analysis.","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fpulse\u002Fskills\u002Fpulse\u002FSKILL.md",[],[],{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":93,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":19},"01M7BERNHYGY035AR00VRT03KE","patent","Patent prior-art and landscape intelligence skill — not generic patent help. Commits to one of five sub-use-cases via forcing intake (novelty search \u002F freedom-to-operate \u002F competitive landscape \u002F acquisition diligence \u002F litigation prior-art) before any search runs. Searches Google Patents, Espacenet, USPTO, and optionally Lens.org for citation-graph signals. Output is an editable Word document (.docx) with verdict, ranked closest art (claim-text extracted), CPC-class-aware landscape, family-resolved hits, geographic coverage, FTO flags where applicable, strategy recommendations, and full audit log. Use when the user asks for patent searching or analysis (e.g., 'prior art search for [invention]', 'freedom to operate analysis for [product]'). Produces search signal, not legal advice — always recommends consulting a patent attorney before filing or licensing decisions. Trademark, copyright, and trade-secret questions are out of scope.","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fpatent\u002Fskills\u002Fpatent\u002FSKILL.md",[],[],{"skillNo":112,"name":113,"nameZh":6,"description":114,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":93,"licenseFileUrl":6,"sourceHtmlUrl":115,"categories":116,"keywords":117,"publishedAt":19},"01M7BERCK1EAKTWW7R436WAR0J","notebooklm","Browser automation skill for controlling Google's NotebookLM. Use when the user wants anything done in NotebookLM (e.g., 'open NotebookLM', 'check my [name] notebook', 'ask my notebook about X', 'add [source] to NotebookLM', 'generate a Video Overview from my notebook', 'use NotebookLM Studio'). Handles reading and querying notebooks, adding sources (URLs, text, files, YouTube links, synthesized content), generating Studio outputs (Audio\u002FVideo Overviews, Mind Maps, Reports incl. Briefing Doc\u002FStudy Guide\u002FFAQ, Flashcards, Quiz, slide decks, infographics — discover the exact set from the live Studio panel; the UI evolves fast), and creating new notebooks. Requires browser automation environment — fails gracefully when unavailable.","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fnotebooklm\u002Fskills\u002Fnotebooklm\u002FSKILL.md",[],[],{"skillNo":119,"name":120,"nameZh":6,"description":121,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":93,"licenseFileUrl":6,"sourceHtmlUrl":122,"categories":123,"keywords":124,"publishedAt":19},"01M7BEQZAZAQRTXFJRY7RHV3TY","litreview","Academic literature orientation skill that searches papers via free keyless APIs (PubMed E-utilities + OpenAlex) by default — with the Consensus MCP as an optional enhancement lane when connected — builds a strategic search plan using PICO (default) or SPIDER \u002F Decomposition \u002F hybrid as fallbacks, and synthesizes findings into a formatted Word (.docx) research guide. Grill-me intake (research question specificity + framework hint + tentative depth) before the recon search; a second forcing checkpoint after Phase 2 confirms framework + sub-areas + depth before searches consume budget. Configurable depth (5\u002F10\u002F20 queries) controls coverage vs. speed. Output is a 'launching pad' — an orientation guide that lets a researcher dive in confidently, not a finished review. Use when the user starts literature-oriented research (e.g., 'litreview on [topic]', 'literature review on [topic]', 'I'm starting a literature review on X', 'I'm writing a paper on X', 'help me research X', 'I'm doing research on X', 'can you help me research X'). Do NOT use for single one-off paper searches wanting a quick list — that's a plain PubMed\u002FOpenAlex (or Consensus) query.","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Flitreview\u002Fskills\u002Flitreview\u002FSKILL.md",[],[],{"skillNo":126,"name":127,"nameZh":6,"description":128,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":93,"licenseFileUrl":6,"sourceHtmlUrl":129,"categories":130,"keywords":131,"publishedAt":19},"01M7BEQKJ45K31QK5VRAQSVJCJ","grants","NIH grant research skill for clinical researchers. Grill-me intake (research idea + career stage + preliminary data + environment + submission posture + known institute targets) locks down the funding strategy before any search runs. Runs a 5-facet Consensus positioning analysis (with draft Significance\u002FInnovation language), maps the research to the right NIH institutes and study sections via RePORTER, finds NOSIs and funded overlap, and produces an editable Word document (.docx) with budget\u002Fscope-aware mechanism recommendations, submission timelines, and a mandatory program officer recommendation. Use when the user asks about research funding or makes any grant-related request (e.g., 'grants for [topic]', 'find grants for my research idea', 'what grants match my research', 'help me find NIH funding', 'grant opportunities for my research'). NIH-only scope — non-NIH funders (PCORI, DOD CDMRP, VA, foundations) are out of scope and flagged at intake.","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fgrants\u002Fskills\u002Fgrants\u002FSKILL.md",[],[]]