localvectordb_server.keymanager module

API Key Management System for LocalVectorDB Server v1.0

This module provides secure API key management using SQLite storage with proper hashing, expiration, and audit trails. Keys are stored separately from the main configuration to improve security.

Features:
  • Secure key hashing with bcrypt

  • Key expiration and rotation

  • Audit trail and usage tracking

  • CLI integration for key management

  • Backward compatibility with config-based keys

Main Components:
  • KeyManager: Core key management functionality

  • KeyRecord: Data class for key metadata

  • CLI integration through auth commands

Security Features:
  • Keys are hashed with bcrypt before storage

  • Generated keys use cryptographically secure random data

  • Support for key expiration and automatic cleanup

  • Audit logging of key usage

  • Soft deletion for revoked keys

Examples

Creating and using the key manager:

from localvectordb_server.key_manager import KeyManager

# Initialize with database path
key_mgr = KeyManager("/path/to/keys.db")

# Create a new API key
key_record = key_mgr.create_key(
    description="CI/CD Pipeline",
    expires_days=90
)
print(f"Generated key: {key_record.plain_key}")
print(f"Key ID: {key_record.id}")

# Validate a key
is_valid = key_mgr.validate_key("lvdb_abcd1234...")

# List active keys
keys = key_mgr.list_keys(active_only=True)

# Revoke a key
key_mgr.revoke_key("key_12345")

CLI usage:

# Create a new key
$ lvdb auth create-key --description "My App" --expires-days 30

# List all keys
$ lvdb auth list-keys

# Revoke a key
$ lvdb auth revoke-key key_12345

# Clean up expired keys
$ lvdb auth prune-expired
class localvectordb_server.keymanager.PermissionLevel(*values)

Bases: Enum

API key permission levels

READ_ONLY = 'read_only'
READ_WRITE = 'read_write'
class localvectordb_server.keymanager.KeyRecord(id: str, key_hash: str, description: str | None = None, created_at: datetime | None = None, expires_at: datetime | None = None, last_used: datetime | None = None, active: bool = True, created_by: str | None = None, permission_level: PermissionLevel = PermissionLevel.READ_WRITE, plain_key: str | None = None)

Bases: object

Represents an API key record with metadata

id: str
key_hash: str
description: str | None = None
created_at: datetime | None = None
expires_at: datetime | None = None
last_used: datetime | None = None
active: bool = True
created_by: str | None = None
permission_level: PermissionLevel = 'read_write'
plain_key: str | None = None
property is_expired: bool

Check if the key is expired

property days_until_expiry: int | None

Get days until expiry, None if no expiration

to_dict() Dict[str, Any]

Convert to dictionary for JSON serialization

classmethod from_db_row(row: Row) KeyRecord

Create KeyRecord from database row

__init__(id: str, key_hash: str, description: str | None = None, created_at: datetime | None = None, expires_at: datetime | None = None, last_used: datetime | None = None, active: bool = True, created_by: str | None = None, permission_level: PermissionLevel = PermissionLevel.READ_WRITE, plain_key: str | None = None) None
class localvectordb_server.keymanager.KeyManager(db_path: str)

Bases: object

Manages API keys with SQLite storage and bcrypt hashing

This class handles the complete lifecycle of API keys including creation, validation, rotation, and cleanup. Keys are stored in a SQLite database with proper security measures.

Initialize KeyManager with database path

Parameters:

db_path (str) – Path to SQLite database file for storing keys

SCHEMA_VERSION = 3
KEY_PREFIX = 'lvdb_'
KEY_LENGTH = 32
KEY_CHARSET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
__init__(db_path: str)

Initialize KeyManager with database path

Parameters:

db_path (str) – Path to SQLite database file for storing keys

create_key(description: str | None = None, expires_days: int | None = None, created_by: str | None = None, permission_level: PermissionLevel = PermissionLevel.READ_WRITE) KeyRecord

Create a new API key

Parameters:
  • description (str, optional) – Human-readable description of the key’s purpose

  • expires_days (int, optional) – Number of days until key expires (None = never expires)

  • created_by (str, optional) – Identifier of who created the key

  • permission_level (PermissionLevel, optional) – Permission level for the key (defaults to READ_WRITE)

Returns:

The created key record with the plain key included

Return type:

KeyRecord

validate_key(key: str, update_last_used: bool = True, prune_expired: bool = False) bool

Validate an API key

Parameters:
  • key (str) – The API key to validate

  • update_last_used (bool, default True) – Whether to update the last_used timestamp

Returns:

True if key is valid and active, False otherwise

Return type:

bool

validate_key_with_permissions(key: str, update_last_used: bool = True, prune_expired: bool = False) tuple[bool, PermissionLevel | None, str | None]

Validate an API key and return its permission level and key_id

Parameters:
  • key (str) – The API key to validate

  • update_last_used (bool, default True) – Whether to update the last_used timestamp

  • prune_expired (bool, default False) – Whether to automatically prune expired keys

Returns:

(is_valid, permission_level, key_id) - permission_level and key_id are None if key is invalid

Return type:

tuple[bool, Optional[PermissionLevel], Optional[str]]

get_key(key_id: str) KeyRecord | None

Get a key record by ID

Parameters:

key_id (str) – The key ID to retrieve

Returns:

The key record if found, None otherwise

Return type:

KeyRecord or None

list_keys(active_only: bool = False, include_expired: bool = True) List[KeyRecord]

List API keys

Parameters:
  • active_only (bool, default False) – Only return active (non-revoked) keys

  • include_expired (bool, default True) – Include expired keys in results

Returns:

List of key records

Return type:

List[KeyRecord]

revoke_key(key_id: str) bool

Revoke (deactivate) an API key

Parameters:

key_id (str) – The key ID to revoke

Returns:

True if key was revoked, False if not found

Return type:

bool

rotate_key(key_id: str) KeyRecord | None

Rotate an API key (create new key, deactivate old one)

Parameters:

key_id (str) – The key ID to rotate

Returns:

The new key record if successful, None if original key not found

Return type:

KeyRecord or None

prune_expired(soft_delete: bool = True) int

Clean up expired keys

Parameters:

soft_delete (bool, default True) – If True, mark as inactive instead of deleting

Returns:

Number of keys pruned

Return type:

int

get_stats() Dict[str, Any]

Get key management statistics

Returns:

Statistics about keys in the system

Return type:

Dict[str, Any]

localvectordb_server.keymanager.get_key_manager(key_db_path: str | None = None) KeyManager

Get a KeyManager instance using configuration

Parameters:

key_db_path (str, optional) – Path to the key database, defaults to “./.lvdb/api_keys.db”

Returns:

Configured KeyManager instance

Return type:

KeyManager