Skip to main content

A Python-wrapped Rust library for RSA JWT generation and validation

Project description

Here’s the updated README with a focus on the features, including the use of jsonwebtoken under the hood and KID rotation support.


Rust-Based RSA JWT Library

This library offers a high-performance, Rust-based JWT solution with Python bindings via PyO3. Designed for security and speed, it incorporates advanced features like KID rotation, blocking claims, and TTL enforcement.


Features

  1. Powered by jsonwebtoken:

    • The library leverages the jsonwebtoken crate, a popular and robust JWT library in Rust.
    • Provides support for industry-standard algorithms (RS256, HS256, and more).
  2. KID Rotation:

    • Supports Key ID (KID) rotation, allowing seamless switching between keys without disrupting existing tokens.
    • Keys are managed via KeyStore, where each key pair can be registered with a unique kid.
  3. Custom Validation Rules:

    • Claim Blocking: Reject tokens containing specific blocked values.
    • Claim Matching: Ensure claims match predefined expected values.
    • TTL Enforcement: Enforce a time-to-live (TTL) for tokens.
  4. Exception Handling:

    • Provides detailed Python exceptions for better catching.
  5. High Performance:

    • Faster token generation and validation compared to PyJWT.

Installation

  1. Clone the repository:

    git clone <repository-url>
    cd <repository-directory>
    
  2. Install dependencies:

    pip install maturin
    
  3. Build and install the Python package:

    maturin develop
    
  4. Verify installation:

    python -c "import key_manager; print('Installed successfully!')"
    

Quick Start

Example Usage

import time
from datetime import datetime, timedelta, timezone
from key_manager import KeyManager, KeyStore, TokenValidation, BlockedKeyError, MissingMatchClaimError, ExpiredToken

# Load keys
private_key_path = "path/to/private_key.pem"
public_key_path = "path/to/public_key.pem"

# Prepare claims
exp = datetime.now(timezone.utc) + timedelta(hours=1)
claims = {
    "sub": "user123",
    "custom_claim": "example_value",
    "exp": int(exp.timestamp()),
    "iat": int(time.time()),
}

# Initialize KeyStore and KeyManager
key_store = KeyStore()
key_store.load_keys("default", private_key_path, public_key_path, "RS256", is_default=True)
key_manager = KeyManager(key_store)

# Generate a token
token = key_manager.generate_token_by_kid("default", claims)
print("Generated Token:", token)

# Validate the token with custom rules
validation = TokenValidation()
validation.claims = {"custom_claim": "example_value"}  # Require exact match
validation.block = {"is_admin": ["False"]}  # Block if "is_admin" is False
validation.ttl = 60  # Enforce TTL of 60 seconds

try:
    decoded = key_manager.verify_token_by_kid(token, "default", validation)
    print("Token is valid. Decoded claims:", decoded)
except BlockedKeyError as e:
    print("BlockedKeyError:", e)
except MissingMatchClaimError as e:
    print("MissingMatchClaimError:", e)
except ExpiredToken as e:
    print("ExpiredToken:", e)
except Exception as e:
    print("Validation failed:", e)

Key Rotation

Key rotation is seamlessly supported:

  1. Register multiple keys using KeyStore.register_keys() or KeyStore.load_keys() methods.
  2. Assign a unique kid to each key.
  3. Specify the desired kid during token generation and validation.

Benchmarking

The provided test script compares the performance of this library against PyJWT.

Run Benchmark

python benchmark.py

Expected Output

Benchmarking PyJWT vs Rust-based RSA JWT

PyJWT:
  Generation time: 0.001234 seconds
  Validation time: 0.001567 seconds

Rust-based RSA JWT:
  Generation time: 0.000789 seconds
  Validation time: 0.000923 seconds

Performance Comparison:
  Token generation: Rust is 1.56x faster than PyJWT
  Token validation: Rust is 1.70x faster than PyJWT

Exception Types

Exception Name Description
BlockedKeyError Raised when a token contains blocked claim values.
MissingMatchClaimError Raised when a claim value doesn't match the expected value.
ExpiredToken Raised when the token exceeds the enforced TTL.
InvalidTokenError Raised for general invalid token errors.
ExpiredSignatureError Raised when the token has expired.
DecodeError Raised for decoding errors.

Testing

Save the provided Python script as benchmark.py and update paths for your key files.


Let me know if further updates are needed!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

jwk_key_manager-0.1.3.tar.gz (23.2 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

jwk_key_manager-0.1.3-cp311-cp311-manylinux_2_28_x86_64.whl (1.0 MB view details)

Uploaded CPython 3.11manylinux: glibc 2.28+ x86-64

jwk_key_manager-0.1.3-cp311-cp311-manylinux_2_28_aarch64.whl (997.5 kB view details)

Uploaded CPython 3.11manylinux: glibc 2.28+ ARM64

File details

Details for the file jwk_key_manager-0.1.3.tar.gz.

File metadata

  • Download URL: jwk_key_manager-0.1.3.tar.gz
  • Upload date:
  • Size: 23.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.2

File hashes

Hashes for jwk_key_manager-0.1.3.tar.gz
Algorithm Hash digest
SHA256 471d4379d1671181857a9f711a401e1c0bc20338007389643bb8c1d404d5c62b
MD5 b6e5cee42c36ac73022c18f4db2edd43
BLAKE2b-256 af98359b614603ce4ed4075b189516cb427bcee76f6ac087f91787baafbdafa7

See more details on using hashes here.

File details

Details for the file jwk_key_manager-0.1.3-cp311-cp311-manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for jwk_key_manager-0.1.3-cp311-cp311-manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 64e96b9f0f00802f31a3f64c124b14d691e35b4c2e1a3a075f368d42cde93680
MD5 a91f1a686182eb7334f17dd5d63cdae7
BLAKE2b-256 c2e99d2d6e9be32ed5ba44fcd116e54f5ccca5d53c5c7005c1aafc2b7c260a6c

See more details on using hashes here.

File details

Details for the file jwk_key_manager-0.1.3-cp311-cp311-manylinux_2_28_aarch64.whl.

File metadata

File hashes

Hashes for jwk_key_manager-0.1.3-cp311-cp311-manylinux_2_28_aarch64.whl
Algorithm Hash digest
SHA256 8438a42a5f49587a9dbe3ec1c813a885475a9746511e450685acb8bdefe5cfb3
MD5 4ca987e83f2af58ad16b30c098b07ae1
BLAKE2b-256 0d2b66f040fdb30c61a5676a88aade4884f4c568f7b4811606784a88467f3119

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page