Zero-config, professional-grade API security manager. Elegant authentication, rate limiting, and audit logging for modern Python APIs.
Project description
🔐 Keymaster HJY
Zero-config, professional-grade API security manager
Elegant authentication, rate limiting, and audit logging for modern Python APIs
🚀 Zero Configuration • 🔒 Production Ready • ⚡ High Performance • 🎯 Framework Agnostic
✨ Why Keymaster HJY?
🚀 Quick Start
Installation
Choose the installation that matches your needs:
# For FastAPI projects
pip install keymaster_hjy[fastapi] -i https://pypi.tuna.tsinghua.edu.cn/simple
# For Flask projects
pip install keymaster_hjy[flask] -i https://pypi.tuna.tsinghua.edu.cn/simple
# With CLI tools for easy setup
pip install keymaster_hjy[cli] -i https://pypi.tuna.tsinghua.edu.cn/simple
# Everything included
pip install keymaster_hjy[all] -i https://pypi.tuna.tsinghua.edu.cn/simple
Interactive Setup
The easiest way to get started is with our interactive CLI:
# Initialize a new project with guided setup
keymaster init
# Or initialize in a specific directory
keymaster init my-secure-api
This will:
- ✅ Guide you through database configuration
- ✅ Set up optional Redis for distributed rate limiting
- ✅ Generate framework-specific example applications
- ✅ Create all necessary configuration files
Manual Configuration
Alternatively, create a mysql.env file manually:
# mysql.env - Database configuration
MYSQL_HOST=your-mysql-host
MYSQL_PORT=3306
MYSQL_USER=your_user
MYSQL_PASSWORD=your_password
MYSQL_DATABASE=your_database
# Optional: Redis for distributed rate limiting
REDIS_HOST=your-redis-host
REDIS_PORT=6379
REDIS_PASSWORD=your_redis_password
Usage Examples
FastAPI Integration
from fastapi import FastAPI
from keymaster_hjy.integrations import fastapi_guard
app = FastAPI()
# Basic protection - requires valid API key
@app.get("/api/data", dependencies=[fastapi_guard()])
async def get_data():
return {"message": "Protected data"}
# Scope-based protection
@app.get("/api/users", dependencies=[fastapi_guard("read:users")])
async def get_users():
return {"users": [...]}
@app.post("/api/users", dependencies=[fastapi_guard("write:users")])
async def create_user():
return {"status": "created"}
Flask Integration
from flask import Flask
from keymaster_hjy.integrations import flask_guard
app = Flask(__name__)
@app.route("/api/data")
@flask_guard() # Basic protection
def get_data():
return {"message": "Protected data"}
@app.route("/api/admin")
@flask_guard("admin:access") # Scope-based protection
def admin_panel():
return {"message": "Admin access granted"}
API Key Management
Creating API Keys
from keymaster_hjy import master
# Create a basic API key
key_info = master.keys.create(
description="My application key",
tags=["production"],
scopes=["read:users", "write:data"]
)
print(f"Key ID: {key_info['id']}")
print(f"API Key: {key_info['key']}") # Store this securely!
Testing Your API
Once you have an API key, test your protected endpoints:
# Test with curl
curl -H "X-API-Key: your-api-key-here" http://localhost:8000/api/data
# Test with httpx (Python)
import httpx
response = httpx.get(
"http://localhost:8000/api/data",
headers={"X-API-Key": "your-api-key-here"}
)
Key Management Operations
# Rotate a key (old key expires after transition period)
new_key = master.keys.rotate(key_id=123, transition_period_hours=24)
# Deactivate a key
master.keys.deactivate(key_id=123)
# Manual validation
try:
master.auth.validate_key("your-key", required_scope="read:data")
print("✅ Key is valid and has required scope")
except Exception as e:
print(f"❌ Validation failed: {e}")
📚 API Reference
Key Management (master.keys)
| Method | Description | Returns |
|---|---|---|
create(description, **opts) |
Create new API key | {'id': int, 'key': str} |
deactivate(key_id) |
Deactivate a key | None |
rotate(key_id, transition_period_hours=24) |
Rotate key with grace period | {'id': int, 'key': str} |
Create Options:
rate_limit: Custom rate limit (e.g.,"100/minute")expires_at: Expiration date (ISO string)tags: List of tags for organizationscopes: List of permission scopes
Authentication (master.auth)
| Method | Description | Exceptions |
|---|---|---|
validate_key(key, **opts) |
Validate API key | InvalidKeyError, KeyExpiredError, RateLimitExceededError, ScopeDeniedError |
Validation Options:
required_scope: Required permission scoperequest_id: Request tracking IDsource_ip: Client IP addressrequest_method: HTTP methodrequest_path: Request path
Framework Integrations
from keymaster_hjy.integrations import fastapi_guard, flask_guard
# FastAPI
@app.get("/path", dependencies=[fastapi_guard("scope?")])
# Flask
@flask_guard("scope?")
🔧 Advanced Features
Custom Rate Limits
# High-frequency API key
key_info = master.keys.create(
description="Batch processing service",
rate_limit="1000/minute" # Custom limit
)
# Different limits for different use cases
analytics_key = master.keys.create(
description="Analytics dashboard",
rate_limit="50/second"
)
Key Organization with Tags
# Organize keys by environment and purpose
prod_key = master.keys.create(
description="Production mobile app",
tags=["production", "mobile", "v2.1"],
scopes=["read:users", "write:analytics"]
)
# Query and manage by tags (future feature)
# keys_by_tag = master.keys.find_by_tags(["production"])
Automatic Key Rotation
# Rotate keys with zero downtime
new_key = master.keys.rotate(
key_id=123,
transition_period_hours=48 # Old key valid for 48h
)
print(f"New key: {new_key['key']}")
print("Update your applications with the new key within 48 hours")
🚨 Error Handling
Keymaster provides clear, actionable error messages:
from keymaster_hjy.exceptions import (
InvalidKeyError,
KeyDeactivatedError,
KeyExpiredError,
RateLimitExceededError,
ScopeDeniedError
)
try:
master.auth.validate_key("your-key", required_scope="read:data")
except InvalidKeyError:
# Key not found or malformed
return {"error": "Invalid API key provided"}
except KeyExpiredError:
# Key has expired
return {"error": "API key expired, please generate a new one"}
except ScopeDeniedError:
# Missing required permissions
return {"error": "Insufficient permissions for this operation"}
except RateLimitExceededError:
# Too many requests
return {"error": "Rate limit exceeded, please try again later"}
HTTP Status Mapping
| Exception | HTTP Status | Description |
|---|---|---|
InvalidKeyError |
401 Unauthorized | Key not found or invalid format |
KeyDeactivatedError |
401 Unauthorized | Key has been deactivated |
KeyExpiredError |
401 Unauthorized | Key has expired |
ScopeDeniedError |
403 Forbidden | Missing required permissions |
RateLimitExceededError |
429 Too Many Requests | Rate limit exceeded |
⚙️ Configuration
Environment Variables
All configuration is done through the mysql.env file:
# Database (Required)
MYSQL_HOST=your-mysql-host
MYSQL_PORT=3306
MYSQL_USER=your-username
MYSQL_PASSWORD=your-password
MYSQL_DATABASE=your-database
# Redis (Optional - for distributed rate limiting)
REDIS_HOST=your-redis-host
REDIS_PORT=6379
REDIS_PASSWORD=your-redis-password
Default Settings
| Setting | Default Value | Description |
|---|---|---|
| Key Prefix | lingchongtong- |
Prefix for generated keys |
| Rate Limit | 100/minute |
Default rate limit for new keys |
| Config Refresh | 30 seconds |
Settings cache refresh interval |
💡 Pro Tip: All settings are stored in your database and can be modified at runtime by updating the
keymaster_settingstable.
🏗️ Architecture
- Zero Configuration: Automatic database schema creation and environment detection
- Security First: Keys are hashed using secure algorithms, never stored in plain text
- Scalable: Redis-backed rate limiting for multi-instance deployments
- Framework Agnostic: Works with FastAPI, Flask, and can be extended to any Python web framework
- Production Ready: Thread-safe, async-compatible, and battle-tested
📝 License
This project is licensed under the MIT License - see the LICENSE file for details.
🤝 Contributing
We welcome contributions! Please see DEVELOPER.md for development setup and guidelines.
Made with ❤️ for the Python community
If you find this project useful, please consider giving it a ⭐ on GitHub!
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file keymaster_hjy-0.0.1.tar.gz.
File metadata
- Download URL: keymaster_hjy-0.0.1.tar.gz
- Upload date:
- Size: 51.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
92a3827da76ee715d8c4163e35f8e4a320b8089702593bac6b4d68f523039a5f
|
|
| MD5 |
c2dc7c31974a1d4c96330abdf0515781
|
|
| BLAKE2b-256 |
e05bad11ecaef892f2e9d9a340239c8ea4e9f01c0808951e873bc49168f791d6
|
File details
Details for the file keymaster_hjy-0.0.1-py3-none-any.whl.
File metadata
- Download URL: keymaster_hjy-0.0.1-py3-none-any.whl
- Upload date:
- Size: 36.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7369a1e0e6f1e9e1dc9e165e5bd55e87e2eec3be2fd211faafc573421cadfbb8
|
|
| MD5 |
76f8ab6d299a66017217d325b9b87f95
|
|
| BLAKE2b-256 |
5263e5c6da4d4a94900a32025bef37ceca9278a797db7d061725966ff94b3f80
|