API Reference¶
This page provides comprehensive documentation for all public classes and functions in the WAuth library.
Main Interface¶
- class wauth.WAuth(db_path='~/.wisrovi/wauth.db', custom_key=None, config_path=None, verbose=False)[source]¶
Bases:
objectMain interface for managing encrypted secrets.
Provides methods for storing, retrieving, deleting, rotating, backing up, and restoring encrypted secrets.
- Parameters:
db_path (str) – Path to the SQLite database file. Defaults to
~/.wisrovi/wauth.db.custom_key (str | None) – Optional custom encryption key string.
config_path (str | None) – Optional path to a TOML configuration file.
verbose (bool) – When
True, emit debug/info/warning logs via loguru. Defaults toFalse.
Example
>>> auth = WAuth() >>> auth.set("MY_KEY", "my-secret") >>> value = auth.get("MY_KEY")
- valid(key, value_to_check)[source]¶
Verify if a stored secret matches the provided value.
This method is more secure than get() when you only need to check a secret’s value, as the secret never leaves the library.
- Parameters:
- Returns:
True if the stored secret matches value_to_check.
- Return type:
Example
>>> auth = WAuth() >>> auth.set("API_KEY", "secret123") >>> auth.valid("API_KEY", "secret123") True >>> auth.valid("API_KEY", "wrong") False
- delete(key)[source]¶
Delete a secret from the vault.
- Parameters:
key (str) – Unique identifier for the secret to remove.
- Raises:
WAuthError – If the key does not exist.
- rotate_key(new_custom_key)[source]¶
Rotate the encryption key and re-encrypt all existing secrets.
Decrypts every secret with the current key, then re-encrypts and stores them with the new key. The internal engine is swapped only if all migrations succeed.
- backup(output_path)[source]¶
Export all secrets to an encrypted backup file.
Creates a JSON file containing all secret keys and their encrypted values (still encrypted — the backup itself is not decrypted).
- Parameters:
output_path (str) – Destination path for the backup file.
- Returns:
The absolute path of the created backup file.
- Raises:
BackupError – If the export fails.
- Return type:
- restore(backup_path)[source]¶
Restore secrets from an encrypted backup file.
Reads a backup file created by
backup()and re-stores all encrypted secrets into the current vault.- Parameters:
backup_path (str) – Path to the backup file.
- Returns:
The number of secrets restored.
- Raises:
RestoreError – If the file cannot be read or parsed.
- Return type:
- async async_set(key, value, ttl=None)[source]¶
Async variant of
set().Runs the synchronous
setin a thread pool to avoid blocking the event loop during I/O-bound database writes.
- async async_delete(key)[source]¶
Async variant of
delete().- Parameters:
key (str) – Unique identifier for the secret to remove.
Functional API¶
- wauth.delete(key)[source]¶
Delete a secret (functional API).
- Parameters:
key (str) – Unique identifier for the secret to remove.
- Raises:
WAuthError – If the key does not exist.
Verbose Control¶
CryptoEngine¶
Cryptographic engine for encrypting and decrypting data using Fernet.
- class wauth.core.CryptoEngine(custom_key=None)[source]¶
Bases:
objectHandles encryption and decryption using Fernet (AES-128-CBC).
The encryption key is derived from a machine-specific identifier, meaning data encrypted on one machine can only be decrypted on that same machine.
- Parameters:
custom_key (str | None) – Optional custom encryption key string. If provided, it is hashed with SHA-256 to produce a deterministic 32-byte key. If
None, the key is derived from the machine identifier.
- decrypt(token)[source]¶
Decrypt a Fernet token back to raw bytes.
- Parameters:
token (str) – Base64-encoded Fernet token.
- Returns:
Decrypted plaintext as bytes.
- Raises:
DecryptionError – If the token is invalid, tampered, or encrypted with a different key.
- Return type:
Vault & SecretModel¶
Persistent storage layer for encrypted secrets using wsqlite.
- class wauth.vault.SecretModel(*, key, value, type='text', created_at=0.0, updated_at=0.0, ttl=None)[source]¶
Bases:
BaseModelPydantic model representing a stored secret.
- Variables:
key (str) – Primary key — unique name of the secret.
value (str) – Encrypted ciphertext of the secret.
type (str) – Secret type, either
"text"or"file".created_at (float) – Unix timestamp when the secret was first stored.
updated_at (float) – Unix timestamp of the last modification.
ttl (float | None) – Optional time-to-live in seconds.
Nonemeans no expiration.
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class wauth.vault.Vault(db_path='~/.wisrovi/wauth.db')[source]¶
Bases:
objectEncrypted secret storage backed by a SQLite database.
- Parameters:
db_path (str) – Path to the SQLite database file. Defaults to
~/.wisrovi/wauth.db.
- db: WSQLite¶
- save(key, encrypted_value, val_type='text', ttl=None)[source]¶
Save or update an encrypted secret in the vault.
Uses
INSERT OR REPLACEsemantics to upsert the secret by key. Timestamps are automatically managed.
- delete(key)[source]¶
Delete a secret from the vault.
- Parameters:
key (str) – Unique identifier for the secret to remove.
- Raises:
KeyNotFoundError – If the key does not exist.
VaultError – If the delete operation fails.
Exceptions¶
Custom exception hierarchy for WAuth.
Provides a structured hierarchy of exceptions that allow callers to distinguish between different failure modes (key not found, decryption failure, vault corruption, backup errors, etc.).
- exception wauth.exceptions.WAuthError[source]¶
Bases:
ExceptionBase exception for all WAuth-related errors.
All custom exceptions inherit from this class, allowing callers to catch any WAuth-specific error with a single
exceptclause.Example
>>> try: ... auth.get("NONEXISTENT") ... except WAuthError as exc: ... print(f"WAuth error: {exc}")
- exception wauth.exceptions.KeyNotFoundError[source]¶
Bases:
WAuthErrorRaised when a requested secret key does not exist in the vault.
Example
>>> try: ... value = auth.get("MISSING_KEY") ... except KeyNotFoundError: ... print("Key not found")
- exception wauth.exceptions.DecryptionError[source]¶
Bases:
WAuthErrorRaised when decryption fails due to wrong key or corrupted data.
This exception replaces the previous silent-failure behaviour that returned empty bytes (
b"") on decryption errors.Example
>>> try: ... engine.decrypt("invalid-token") ... except DecryptionError: ... print("Cannot decrypt — wrong key or corrupted data")
- exception wauth.exceptions.VaultError[source]¶
Bases:
WAuthErrorRaised when a vault operation fails (database corruption, I/O error).
Example
>>> try: ... vault.save("KEY", "value") ... except VaultError: ... print("Vault storage error")
- exception wauth.exceptions.BackupError[source]¶
Bases:
WAuthErrorRaised when a backup or export operation fails.
Example
>>> try: ... auth.backup("backup.wauth") ... except BackupError: ... print("Backup failed")
- exception wauth.exceptions.RestoreError[source]¶
Bases:
WAuthErrorRaised when a restore or import operation fails.
Example
>>> try: ... auth.restore("backup.wauth") ... except RestoreError: ... print("Restore failed")
- exception wauth.exceptions.RotationError[source]¶
Bases:
WAuthErrorRaised when a key or secret rotation operation fails.
Example
>>> try: ... auth.rotate_key() ... except RotationError: ... print("Key rotation failed")
- exception wauth.exceptions.ConfigurationError[source]¶
Bases:
WAuthErrorRaised when configuration loading or validation fails.
Example
>>> try: ... auth = WAuth(config_path="bad.toml") ... except ConfigurationError: ... print("Invalid configuration file")
Deprecation Utilities¶
Deprecation utilities for WAuth.
Provides a decorator and helper functions to mark deprecated APIs with proper warnings, enabling graceful migration across versions.
- wauth.deprecation.deprecated(since, removal, replacement=None, reason='')[source]¶
Mark a function or method as deprecated.
Emits a
DeprecationWarningon first use and logs the deprecation via loguru.- Parameters:
- Returns:
Decorated function that emits a warning on invocation.
- Return type:
Callable[[T], T]
Example
>>> @deprecated(since="1.6.0", removal="2.0.0", replacement="get_secret") ... def old_method(): ... pass
Utilities¶
Platform utilities for machine identification and key derivation.
- wauth.utils.get_machine_id()[source]¶
Retrieve a unique machine identifier in a cross-platform way.
Attempts platform-specific methods in the following order:
Linux: Reads
/etc/machine-idor/var/lib/dbus/machine-id.Windows: Queries
wmic csproduct get uuid.macOS: Extracts
IOPlatformUUIDfromioreg.
Falls back to
platform.node()(hostname) if all methods fail.- Returns:
A string representing the machine ID.
- Return type:
Drivers¶
DriverFactory¶
- class wauth.drivers.DriverFactory[source]¶
Bases:
objectFactory for managing secret drivers (local and Docker).
Automatically selects the appropriate driver based on the runtime environment.
LocalDriver¶
- class wauth.drivers.local.LocalDriver(custom_key=None)[source]¶
Bases:
objectDriver that stores secrets locally using Fernet encryption.
Combines the cryptographic engine with the SQLite-backed vault for persistent, machine-locked secret storage.
- Parameters:
custom_key (str | None) – Optional custom encryption key string.
- delete_secret(key)[source]¶
Delete a secret from the vault.
- Parameters:
key (str) – Unique identifier for the secret to remove.
- Raises:
KeyNotFoundError – If the key does not exist.
- rotate_key(new_custom_key, keys_to_migrate=None)[source]¶
Rotate the encryption key and re-encrypt existing secrets.
Creates a new CryptoEngine with the provided key, decrypts all existing secrets with the current engine, and re-encrypts them with the new engine.
- Parameters:
- Returns:
A dictionary mapping each key to a boolean indicating success (
True) or failure (False).- Return type:
DockerDriver¶
- class wauth.drivers.docker.DockerDriver(secrets_path='/run/secrets')[source]¶
Bases:
objectDriver for reading secrets from a Docker container’s filesystem.
Docker injects secrets as files under
/run/secrets. This driver reads from that path when running inside a container.Note
This driver is read-only. Writing secrets is handled by
LocalDriver.- Parameters:
secrets_path (str) – Base path where Docker secrets are mounted. Defaults to
/run/secrets.