API Reference

This page provides the complete API reference for Lynguine’s secure credential management system.

Core Functions

Lynguine Security Module

This module provides secure credential management, access control, and auditing for the Lynguine data processing library.

Main components: - Credential management with multiple backend support - Access control and authorization - Security audit logging - Secure error handling and logging - Migration tools for transitioning to secure credentials

class lynguine.security.CredentialProvider(name=None)[source]

Bases: ABC

Abstract base class for credential providers.

Credential providers implement different backends for storing and retrieving credentials securely.

Initialize the credential provider.

Parameters:

name (str) – Optional name for this provider instance

abstract get_credential(key, **kwargs)[source]

Retrieve a credential by key.

Parameters:
  • key (str) – The credential key/identifier

  • kwargs – Additional provider-specific parameters

Returns:

The credential data or None if not found

Return type:

Optional[Dict[str, Any]]

Raises:

CredentialError – If credential retrieval fails

abstract set_credential(key, value, **kwargs)[source]

Store a credential.

Parameters:
  • key (str) – The credential key/identifier

  • value (Dict[str, Any]) – The credential data to store

  • kwargs – Additional provider-specific parameters

Raises:

CredentialError – If credential storage fails

Return type:

None

abstract delete_credential(key, **kwargs)[source]

Delete a credential.

Parameters:
  • key (str) – The credential key/identifier

  • kwargs – Additional provider-specific parameters

Raises:

CredentialError – If credential deletion fails

Return type:

None

abstract list_credentials(**kwargs)[source]

List available credential keys.

Parameters:

kwargs – Additional provider-specific parameters

Returns:

List of credential keys

Return type:

List[str]

Raises:

CredentialError – If listing fails

validate_credential(key, value)[source]

Validate a credential’s format and content.

Parameters:
  • key (str) – The credential key/identifier

  • value (Dict[str, Any]) – The credential data to validate

Returns:

True if valid, False otherwise

Return type:

bool

class lynguine.security.EnvironmentCredentialProvider(prefix='LYNGUINE_CRED', name=None)[source]

Bases: CredentialProvider

Credential provider that retrieves credentials from environment variables.

This provider supports: - Direct environment variable lookup - Prefix-based variable naming (e.g., LYNGUINE_CRED_<KEY>) - JSON-encoded credential values - Validation of environment variable names

Initialize the environment credential provider.

Parameters:
  • prefix (str) – Prefix for environment variable names

  • name (str) – Optional name for this provider instance

get_credential(key, **kwargs)[source]

Retrieve a credential from environment variables.

Parameters:

key (str) – The credential key/identifier

Returns:

The credential data or None if not found

Return type:

Optional[Dict[str, Any]]

set_credential(key, value, **kwargs)[source]

Store a credential in environment variables (current process only).

Note: This only affects the current process and is not persistent.

Parameters:
  • key (str) – The credential key/identifier

  • value (Dict[str, Any]) – The credential data to store

Return type:

None

delete_credential(key, **kwargs)[source]

Delete a credential from environment variables (current process only).

Parameters:

key (str) – The credential key/identifier

Return type:

None

list_credentials(**kwargs)[source]

List available credentials in environment variables.

Returns:

List of credential keys

Return type:

List[str]

validate_credential(key, value)

Validate a credential’s format and content.

Parameters:
  • key (str) – The credential key/identifier

  • value (Dict[str, Any]) – The credential data to validate

Returns:

True if valid, False otherwise

Return type:

bool

class lynguine.security.EncryptedFileCredentialProvider(storage_path=None, master_key=None, name=None)[source]

Bases: CredentialProvider

Credential provider that stores encrypted credentials in files.

This provider uses Fernet (symmetric encryption) with a key derived from a master password using PBKDF2.

Initialize the encrypted file credential provider.

Parameters:
  • storage_path (str) – Path to store encrypted credential files

  • master_key (str) – Master key/password for encryption

  • name (str) – Optional name for this provider instance

Raises:

CredentialEncryptionError – If cryptography is not available

get_credential(key, **kwargs)[source]

Retrieve and decrypt a credential from file.

Parameters:

key (str) – The credential key/identifier

Returns:

The credential data or None if not found

Return type:

Optional[Dict[str, Any]]

set_credential(key, value, **kwargs)[source]

Encrypt and store a credential to file.

Parameters:
  • key (str) – The credential key/identifier

  • value (Dict[str, Any]) – The credential data to store

Return type:

None

delete_credential(key, **kwargs)[source]

Delete a credential file.

Parameters:

key (str) – The credential key/identifier

Return type:

None

list_credentials(**kwargs)[source]

List available credentials (by decrypting and reading metadata).

Note: This requires decrypting all credential files.

Returns:

List of credential keys

Return type:

List[str]

validate_credential(key, value)

Validate a credential’s format and content.

Parameters:
  • key (str) – The credential key/identifier

  • value (Dict[str, Any]) – The credential data to validate

Returns:

True if valid, False otherwise

Return type:

bool

class lynguine.security.CredentialManager(providers=None, cache_ttl=300, enable_cache=True)[source]

Bases: object

Central credential management system with support for multiple providers.

The CredentialManager coordinates credential access across different providers with caching, fallback, and validation support.

Initialize the credential manager.

Parameters:
  • providers (List[CredentialProvider]) – List of credential providers to use

  • cache_ttl (int) – Cache time-to-live in seconds

  • enable_cache (bool) – Whether to enable credential caching

add_provider(provider, priority=None)[source]

Add a credential provider.

Parameters:
  • provider (CredentialProvider) – The credential provider to add

  • priority (int) – Optional priority (lower = higher priority)

Return type:

None

remove_provider(provider)[source]

Remove a credential provider.

Parameters:

provider (CredentialProvider) – The credential provider to remove

Return type:

None

register_validator(credential_type, validator)[source]

Register a validator for a specific credential type.

Parameters:
  • credential_type (str) – The type of credential

  • validator (Callable) – Validation function

Return type:

None

get_credential(key, credential_type=None, use_cache=True, **kwargs)[source]

Retrieve a credential from available providers.

Parameters:
  • key (str) – The credential key/identifier

  • credential_type (str) – Optional credential type for validation

  • use_cache (bool) – Whether to use cache (if enabled)

Returns:

The credential data or None if not found

Return type:

Optional[Dict[str, Any]]

Raises:
set_credential(key, value, provider_name=None, credential_type=None, **kwargs)[source]

Store a credential using a specific provider.

Parameters:
  • key (str) – The credential key/identifier

  • value (Dict[str, Any]) – The credential data to store

  • provider_name (str) – Optional specific provider to use

  • credential_type (str) – Optional credential type for validation

Raises:
Return type:

None

delete_credential(key, provider_name=None, **kwargs)[source]

Delete a credential.

Parameters:
  • key (str) – The credential key/identifier

  • provider_name (str) – Optional specific provider to use

Return type:

None

list_credentials(provider_name=None)[source]

List available credentials.

Parameters:

provider_name (str) – Optional specific provider to query

Returns:

List of credential keys

Return type:

List[str]

lynguine.security.get_credential_manager()[source]

Get or create the global credential manager instance.

Returns:

The global credential manager

Return type:

CredentialManager

lynguine.security.set_credential_manager(manager)[source]

Set a custom global credential manager.

Parameters:

manager (CredentialManager) – The credential manager to use

Return type:

None

lynguine.security.get_credential(key, credential_type=None, default=None)[source]

Get a credential using the global credential manager.

Parameters:
  • key (str) – The credential key/identifier

  • credential_type (str) – Optional credential type for validation

  • default (Any) – Default value if credential not found

Returns:

The credential data or default

Return type:

Optional[Dict[str, Any]]

lynguine.security.set_credential(key, value, credential_type=None)[source]

Set a credential using the global credential manager.

Parameters:
  • key (str) – The credential key/identifier

  • value (Dict[str, Any]) – The credential data to store

  • credential_type (str) – Optional credential type for validation

Return type:

None

exception lynguine.security.CredentialError[source]

Bases: Exception

Base exception for credential-related errors.

add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception lynguine.security.CredentialNotFoundError[source]

Bases: CredentialError

Raised when a credential cannot be found.

add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception lynguine.security.CredentialValidationError[source]

Bases: CredentialError

Raised when credential validation fails.

add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception lynguine.security.CredentialEncryptionError[source]

Bases: CredentialError

Raised when credential encryption/decryption fails.

add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class lynguine.security.CredentialCache(default_ttl=300)[source]

Bases: object

Thread-safe cache for credentials with TTL support.

Initialize the credential cache.

Parameters:

default_ttl (int) – Default time-to-live in seconds

get(key)[source]

Get a credential from cache if not expired.

Parameters:

key (str) – The credential key

Returns:

The cached credential or None

Return type:

Optional[Dict[str, Any]]

set(key, value, ttl=None)[source]

Store a credential in cache with TTL.

Parameters:
  • key (str) – The credential key

  • value (Dict[str, Any]) – The credential value

  • ttl (int) – Time-to-live in seconds (optional)

Return type:

None

invalidate(key)[source]

Remove a credential from cache.

Parameters:

key (str) – The credential key

Return type:

None

clear()[source]

Clear all cached credentials.

Return type:

None

class lynguine.security.AccessLevel(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

Access levels for credential operations.

NONE = 0
READ = 1
WRITE = 2
DELETE = 3
ADMIN = 4
class lynguine.security.AuditEventType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

Types of audit events.

CREDENTIAL_ACCESS = 'credential_access'
CREDENTIAL_CREATE = 'credential_create'
CREDENTIAL_UPDATE = 'credential_update'
CREDENTIAL_DELETE = 'credential_delete'
ACCESS_DENIED = 'access_denied'
VALIDATION_FAILED = 'validation_failed'
AUTHENTICATION_FAILED = 'authentication_failed'
RATE_LIMIT_EXCEEDED = 'rate_limit_exceeded'
class lynguine.security.AuditEvent(event_type, credential_key, user=None, context=None, success=True, details=None)[source]

Bases: object

Represents a security audit event.

Initialize an audit event.

Parameters:
  • event_type (AuditEventType) – Type of event

  • credential_key (str) – The credential key involved

  • user (str) – User performing the action

  • context (str) – Context/source of the operation

  • success (bool) – Whether the operation succeeded

  • details (Dict[str, Any]) – Additional event details

to_dict()[source]

Convert event to dictionary.

Returns:

Event as dictionary

Return type:

Dict[str, Any]

to_json()[source]

Convert event to JSON string.

Returns:

Event as JSON

Return type:

str

class lynguine.security.AuditLogger(log_path=None, enable_console=False, enable_file=True)[source]

Bases: object

Audit logger for credential security events.

Logs security events to structured logs with rotation and tamper detection.

Initialize the audit logger.

Parameters:
  • log_path (str) – Path to audit log file

  • enable_console (bool) – Whether to log to console

  • enable_file (bool) – Whether to log to file

log_event(event)[source]

Log an audit event.

Parameters:

event (AuditEvent) – The audit event to log

Return type:

None

query_events(event_type=None, user=None, start_time=None, end_time=None, limit=100)[source]

Query audit events with filters.

Parameters:
  • event_type (AuditEventType) – Filter by event type

  • user (str) – Filter by user

  • start_time (datetime) – Filter by start time

  • end_time (datetime) – Filter by end time

  • limit (int) – Maximum number of events to return

Returns:

List of matching events

Return type:

List[Dict[str, Any]]

class lynguine.security.AccessPolicy[source]

Bases: object

Access control policy for credentials.

Defines who can access which credentials with what permissions.

Initialize the access policy.

add_rule(credential_pattern, user_pattern='*', context_pattern='*', access_level=AccessLevel.READ)[source]

Add an access control rule.

Parameters:
  • credential_pattern (str) – Credential key pattern (supports wildcards)

  • user_pattern (str) – User pattern (supports wildcards)

  • context_pattern (str) – Context pattern (supports wildcards)

  • access_level (AccessLevel) – Access level to grant

Return type:

None

check_access(credential_key, operation, user=None, context=None)[source]

Check if access is allowed.

Parameters:
  • credential_key (str) – The credential key

  • operation (AccessLevel) – Required access level

  • user (str) – User requesting access

  • context (str) – Context of the request

Returns:

True if access allowed, False otherwise

Return type:

bool

class lynguine.security.RateLimiter(max_requests=100, time_window=60)[source]

Bases: object

Rate limiter for credential access operations.

Prevents brute force attacks and excessive credential access.

Initialize the rate limiter.

Parameters:
  • max_requests (int) – Maximum requests per time window

  • time_window (int) – Time window in seconds

check_rate_limit(key, user=None)[source]

Check if request is within rate limit.

Parameters:
  • key (str) – Identifier for rate limiting (e.g., credential key)

  • user (str) – User making the request

Returns:

True if within limit, False otherwise

Return type:

bool

class lynguine.security.CredentialAccessController(audit_logger=None, access_policy=None, rate_limiter=None)[source]

Bases: object

Integrated access controller for credential operations.

Combines access policy, rate limiting, and audit logging.

Initialize the access controller.

Parameters:
authorize_access(credential_key, operation, user=None, context=None)[source]

Authorize credential access.

Parameters:
  • credential_key (str) – The credential key

  • operation (AccessLevel) – Required access level

  • user (str) – User requesting access

  • context (str) – Context of the request

Raises:
Return type:

None

lynguine.security.get_access_controller()[source]

Get or create the global access controller.

Returns:

The global access controller

Return type:

CredentialAccessController

lynguine.security.set_access_controller(controller)[source]

Set a custom global access controller.

Parameters:

controller (CredentialAccessController) – The access controller to use

Return type:

None

exception lynguine.security.AccessControlError[source]

Bases: Exception

Base exception for access control errors.

add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception lynguine.security.AccessDeniedError[source]

Bases: AccessControlError

Raised when access is denied.

add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception lynguine.security.RateLimitError[source]

Bases: AccessControlError

Raised when rate limit is exceeded.

add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class lynguine.security.SanitizingFormatter(fmt=None, datefmt=None, style='%', additional_patterns=None)[source]

Bases: Formatter

Logging formatter that sanitizes sensitive information.

This formatter automatically redacts sensitive patterns like API keys, passwords, and tokens from log messages.

Initialize the sanitizing formatter.

Parameters:
  • fmt (str) – Log format string

  • datefmt (str) – Date format string

  • style (str) – Format style (‘%’, ‘{’, or ‘$’)

  • additional_patterns (List[tuple]) – Additional (pattern, replacement) tuples

format(record)[source]

Format log record with sanitization.

Parameters:

record (logging.LogRecord) – Log record to format

Returns:

Formatted and sanitized log message

Return type:

str

sanitize(text)[source]

Sanitize text by removing sensitive patterns.

Parameters:

text (str) – Text to sanitize

Returns:

Sanitized text

Return type:

str

converter()
localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,

tm_sec,tm_wday,tm_yday,tm_isdst)

Convert seconds since the Epoch to a time tuple expressing local time. When ‘seconds’ is not passed in, convert the current time instead.

default_msec_format = '%s,%03d'
default_time_format = '%Y-%m-%d %H:%M:%S'
formatException(ei)

Format and return the specified exception information as a string.

This default implementation just uses traceback.print_exception()

formatMessage(record)
formatStack(stack_info)

This method is provided as an extension point for specialized formatting of stack information.

The input data is a string as returned from a call to traceback.print_stack(), but with the last trailing newline removed.

The base implementation just returns the value passed in.

formatTime(record, datefmt=None)

Return the creation time of the specified LogRecord as formatted text.

This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, an ISO8601-like (or RFC 3339-like) format is used. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the ‘converter’ attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the ‘converter’ attribute in the Formatter class.

usesTime()

Check if the format uses the creation time of the record.

class lynguine.security.SecureExceptionHandler[source]

Bases: object

Exception handler that sanitizes sensitive information from exceptions.

Initialize the secure exception handler.

sanitize_exception(exc)[source]

Sanitize an exception’s message.

Parameters:

exc (Exception) – The exception to sanitize

Returns:

Exception with sanitized message

Return type:

Exception

sanitize_text(text)[source]

Sanitize text by removing sensitive patterns.

Parameters:

text (str) – Text to sanitize

Returns:

Sanitized text

Return type:

str

sanitize_traceback(tb_str)[source]

Sanitize a traceback string.

Parameters:

tb_str (str) – Traceback string

Returns:

Sanitized traceback

Return type:

str

format_exception(exc_type, exc_value, exc_traceback)[source]

Format an exception with sanitized information.

Parameters:
  • exc_type (type) – Exception type

  • exc_value (Exception) – Exception instance

  • exc_traceback (Any) – Exception traceback

Returns:

Formatted and sanitized exception

Return type:

str

class lynguine.security.SecureLogger(name, logger=None)[source]

Bases: object

Wrapper around standard logger with automatic sanitization.

Initialize secure logger.

Parameters:
  • name (str) – Logger name

  • logger (logging.Logger) – Underlying logger (creates new if None)

debug(msg, *args, **kwargs)[source]

Log debug message with sanitization.

Parameters:

msg (str)

info(msg, *args, **kwargs)[source]

Log info message with sanitization.

Parameters:

msg (str)

warning(msg, *args, **kwargs)[source]

Log warning message with sanitization.

Parameters:

msg (str)

error(msg, *args, **kwargs)[source]

Log error message with sanitization.

Parameters:

msg (str)

critical(msg, *args, **kwargs)[source]

Log critical message with sanitization.

Parameters:

msg (str)

exception(msg, *args, **kwargs)[source]

Log exception with sanitized traceback.

Parameters:

msg (str)

lynguine.security.setup_secure_logging(logger=None, level=20, format_string=None, additional_patterns=None)[source]

Set up secure logging with sanitization for a logger.

Parameters:
  • logger (logging.Logger) – Logger to configure (None for root logger)

  • level (int) – Logging level

  • format_string (str) – Custom format string

  • additional_patterns (List[tuple]) – Additional sanitization patterns

Returns:

Configured logger

Return type:

logging.Logger

lynguine.security.get_secure_logger(name)[source]

Get or create a secure logger.

Parameters:

name (str) – Logger name

Returns:

Secure logger instance

Return type:

SecureLogger

lynguine.security.sanitize_dict(data, sensitive_keys=None)[source]

Sanitize a dictionary by redacting sensitive keys.

Parameters:
  • data (Dict[str, Any]) – Dictionary to sanitize

  • sensitive_keys (List[str]) – List of keys to redact (case-insensitive)

Returns:

Sanitized dictionary

Return type:

Dict[str, Any]

lynguine.security.secure_repr(obj, max_len=100)[source]

Get a secure string representation of an object.

This function attempts to sanitize the repr() output to avoid exposing sensitive information.

Parameters:
  • obj (Any) – Object to represent

  • max_len (int) – Maximum length of representation

Returns:

Secure representation

Return type:

str

class lynguine.security.CredentialMigrator(credential_manager=None, backup_dir=None)[source]

Bases: object

Tool for migrating credentials to secure storage.

This class helps migrate from: - Plain text configuration files - Environment variables (documentation only) - Legacy credential storage

To the new secure credential management system.

Initialize the credential migrator.

Parameters:
  • credential_manager (CredentialManager) – Credential manager to use (uses global if None)

  • backup_dir (str) – Directory for backups

backup_file(file_path)[source]

Create a backup of a file before migration.

Parameters:

file_path (str) – Path to file to backup

Returns:

Path to backup file

Return type:

str

migrate_yaml_config(config_file, credential_mappings, dry_run=False)[source]

Migrate credentials from a YAML configuration file.

Parameters:
  • config_file (str) – Path to YAML configuration file

  • credential_mappings (Dict[str, str]) – Map of config keys to credential names

  • dry_run (bool) – If True, don’t make changes (default: False)

Returns:

Migration report

Return type:

Dict[str, Any]

migrate_google_sheets_credentials(config_file, credential_name='google_sheets_oauth', dry_run=False)[source]

Migrate Google Sheets credentials specifically.

Parameters:
  • config_file (str) – Path to configuration file

  • credential_name (str) – Name for the credential in secure storage

  • dry_run (bool) – If True, don’t make changes

Returns:

Migration report

Return type:

Dict[str, Any]

generate_environment_variable_script(credentials, output_file=None, shell='bash')[source]

Generate a shell script to set environment variables for credentials.

Parameters:
  • credentials (Dict[str, Dict[str, Any]]) – Dictionary of credential_name -> credential_value

  • output_file (str) – Path to output script (optional)

  • shell (str) – Shell type (“bash” or “fish”)

Returns:

Script content

Return type:

str

validate_migration(config_file)[source]

Validate that a migrated configuration works correctly.

Parameters:

config_file (str) – Path to configuration file

Returns:

Validation report

Return type:

Dict[str, Any]

rollback(backup_path)[source]

Rollback a migration by restoring from backup.

Parameters:

backup_path (str) – Path to backup file

Return type:

None

exception lynguine.security.MigrationError[source]

Bases: Exception

Exception raised during migration.

add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

lynguine.security.create_migration_guide()[source]

Create a migration guide document.

Returns:

Migration guide text

Return type:

str

lynguine.security.save_migration_guide(output_file=None)[source]

Save the migration guide to a file.

Parameters:

output_file (str) – Path to output file (optional)

Returns:

Path to saved file

Return type:

str

Credential Providers

Secure credential management for Lynguine.

This module provides secure credential storage, retrieval, and management with support for multiple backends including environment variables, encrypted files, and cloud vaults.

exception lynguine.security.credentials.CredentialError[source]

Bases: Exception

Base exception for credential-related errors.

add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception lynguine.security.credentials.CredentialNotFoundError[source]

Bases: CredentialError

Raised when a credential cannot be found.

add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception lynguine.security.credentials.CredentialValidationError[source]

Bases: CredentialError

Raised when credential validation fails.

add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception lynguine.security.credentials.CredentialEncryptionError[source]

Bases: CredentialError

Raised when credential encryption/decryption fails.

add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class lynguine.security.credentials.CredentialProvider(name=None)[source]

Bases: ABC

Abstract base class for credential providers.

Credential providers implement different backends for storing and retrieving credentials securely.

Initialize the credential provider.

Parameters:

name (str) – Optional name for this provider instance

abstract get_credential(key, **kwargs)[source]

Retrieve a credential by key.

Parameters:
  • key (str) – The credential key/identifier

  • kwargs – Additional provider-specific parameters

Returns:

The credential data or None if not found

Return type:

Optional[Dict[str, Any]]

Raises:

CredentialError – If credential retrieval fails

abstract set_credential(key, value, **kwargs)[source]

Store a credential.

Parameters:
  • key (str) – The credential key/identifier

  • value (Dict[str, Any]) – The credential data to store

  • kwargs – Additional provider-specific parameters

Raises:

CredentialError – If credential storage fails

Return type:

None

abstract delete_credential(key, **kwargs)[source]

Delete a credential.

Parameters:
  • key (str) – The credential key/identifier

  • kwargs – Additional provider-specific parameters

Raises:

CredentialError – If credential deletion fails

Return type:

None

abstract list_credentials(**kwargs)[source]

List available credential keys.

Parameters:

kwargs – Additional provider-specific parameters

Returns:

List of credential keys

Return type:

List[str]

Raises:

CredentialError – If listing fails

validate_credential(key, value)[source]

Validate a credential’s format and content.

Parameters:
  • key (str) – The credential key/identifier

  • value (Dict[str, Any]) – The credential data to validate

Returns:

True if valid, False otherwise

Return type:

bool

class lynguine.security.credentials.EnvironmentCredentialProvider(prefix='LYNGUINE_CRED', name=None)[source]

Bases: CredentialProvider

Credential provider that retrieves credentials from environment variables.

This provider supports: - Direct environment variable lookup - Prefix-based variable naming (e.g., LYNGUINE_CRED_<KEY>) - JSON-encoded credential values - Validation of environment variable names

Initialize the environment credential provider.

Parameters:
  • prefix (str) – Prefix for environment variable names

  • name (str) – Optional name for this provider instance

get_credential(key, **kwargs)[source]

Retrieve a credential from environment variables.

Parameters:

key (str) – The credential key/identifier

Returns:

The credential data or None if not found

Return type:

Optional[Dict[str, Any]]

set_credential(key, value, **kwargs)[source]

Store a credential in environment variables (current process only).

Note: This only affects the current process and is not persistent.

Parameters:
  • key (str) – The credential key/identifier

  • value (Dict[str, Any]) – The credential data to store

Return type:

None

delete_credential(key, **kwargs)[source]

Delete a credential from environment variables (current process only).

Parameters:

key (str) – The credential key/identifier

Return type:

None

list_credentials(**kwargs)[source]

List available credentials in environment variables.

Returns:

List of credential keys

Return type:

List[str]

validate_credential(key, value)

Validate a credential’s format and content.

Parameters:
  • key (str) – The credential key/identifier

  • value (Dict[str, Any]) – The credential data to validate

Returns:

True if valid, False otherwise

Return type:

bool

class lynguine.security.credentials.EncryptedFileCredentialProvider(storage_path=None, master_key=None, name=None)[source]

Bases: CredentialProvider

Credential provider that stores encrypted credentials in files.

This provider uses Fernet (symmetric encryption) with a key derived from a master password using PBKDF2.

Initialize the encrypted file credential provider.

Parameters:
  • storage_path (str) – Path to store encrypted credential files

  • master_key (str) – Master key/password for encryption

  • name (str) – Optional name for this provider instance

Raises:

CredentialEncryptionError – If cryptography is not available

get_credential(key, **kwargs)[source]

Retrieve and decrypt a credential from file.

Parameters:

key (str) – The credential key/identifier

Returns:

The credential data or None if not found

Return type:

Optional[Dict[str, Any]]

set_credential(key, value, **kwargs)[source]

Encrypt and store a credential to file.

Parameters:
  • key (str) – The credential key/identifier

  • value (Dict[str, Any]) – The credential data to store

Return type:

None

delete_credential(key, **kwargs)[source]

Delete a credential file.

Parameters:

key (str) – The credential key/identifier

Return type:

None

list_credentials(**kwargs)[source]

List available credentials (by decrypting and reading metadata).

Note: This requires decrypting all credential files.

Returns:

List of credential keys

Return type:

List[str]

validate_credential(key, value)

Validate a credential’s format and content.

Parameters:
  • key (str) – The credential key/identifier

  • value (Dict[str, Any]) – The credential data to validate

Returns:

True if valid, False otherwise

Return type:

bool

class lynguine.security.credentials.CredentialCache(default_ttl=300)[source]

Bases: object

Thread-safe cache for credentials with TTL support.

Initialize the credential cache.

Parameters:

default_ttl (int) – Default time-to-live in seconds

get(key)[source]

Get a credential from cache if not expired.

Parameters:

key (str) – The credential key

Returns:

The cached credential or None

Return type:

Optional[Dict[str, Any]]

set(key, value, ttl=None)[source]

Store a credential in cache with TTL.

Parameters:
  • key (str) – The credential key

  • value (Dict[str, Any]) – The credential value

  • ttl (int) – Time-to-live in seconds (optional)

Return type:

None

invalidate(key)[source]

Remove a credential from cache.

Parameters:

key (str) – The credential key

Return type:

None

clear()[source]

Clear all cached credentials.

Return type:

None

class lynguine.security.credentials.CredentialManager(providers=None, cache_ttl=300, enable_cache=True)[source]

Bases: object

Central credential management system with support for multiple providers.

The CredentialManager coordinates credential access across different providers with caching, fallback, and validation support.

Initialize the credential manager.

Parameters:
  • providers (List[CredentialProvider]) – List of credential providers to use

  • cache_ttl (int) – Cache time-to-live in seconds

  • enable_cache (bool) – Whether to enable credential caching

add_provider(provider, priority=None)[source]

Add a credential provider.

Parameters:
  • provider (CredentialProvider) – The credential provider to add

  • priority (int) – Optional priority (lower = higher priority)

Return type:

None

remove_provider(provider)[source]

Remove a credential provider.

Parameters:

provider (CredentialProvider) – The credential provider to remove

Return type:

None

register_validator(credential_type, validator)[source]

Register a validator for a specific credential type.

Parameters:
  • credential_type (str) – The type of credential

  • validator (Callable) – Validation function

Return type:

None

get_credential(key, credential_type=None, use_cache=True, **kwargs)[source]

Retrieve a credential from available providers.

Parameters:
  • key (str) – The credential key/identifier

  • credential_type (str) – Optional credential type for validation

  • use_cache (bool) – Whether to use cache (if enabled)

Returns:

The credential data or None if not found

Return type:

Optional[Dict[str, Any]]

Raises:
set_credential(key, value, provider_name=None, credential_type=None, **kwargs)[source]

Store a credential using a specific provider.

Parameters:
  • key (str) – The credential key/identifier

  • value (Dict[str, Any]) – The credential data to store

  • provider_name (str) – Optional specific provider to use

  • credential_type (str) – Optional credential type for validation

Raises:
Return type:

None

delete_credential(key, provider_name=None, **kwargs)[source]

Delete a credential.

Parameters:
  • key (str) – The credential key/identifier

  • provider_name (str) – Optional specific provider to use

Return type:

None

list_credentials(provider_name=None)[source]

List available credentials.

Parameters:

provider_name (str) – Optional specific provider to query

Returns:

List of credential keys

Return type:

List[str]

lynguine.security.credentials.get_credential_manager()[source]

Get or create the global credential manager instance.

Returns:

The global credential manager

Return type:

CredentialManager

lynguine.security.credentials.set_credential_manager(manager)[source]

Set a custom global credential manager.

Parameters:

manager (CredentialManager) – The credential manager to use

Return type:

None

lynguine.security.credentials.get_credential(key, credential_type=None, default=None)[source]

Get a credential using the global credential manager.

Parameters:
  • key (str) – The credential key/identifier

  • credential_type (str) – Optional credential type for validation

  • default (Any) – Default value if credential not found

Returns:

The credential data or default

Return type:

Optional[Dict[str, Any]]

lynguine.security.credentials.set_credential(key, value, credential_type=None)[source]

Set a credential using the global credential manager.

Parameters:
  • key (str) – The credential key/identifier

  • value (Dict[str, Any]) – The credential data to store

  • credential_type (str) – Optional credential type for validation

Return type:

None

Access Control

Access control and auditing for credential management.

This module provides role-based access control, credential usage auditing, and security event logging for the credential management system.

class lynguine.security.access_control.AccessLevel(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

Access levels for credential operations.

NONE = 0
READ = 1
WRITE = 2
DELETE = 3
ADMIN = 4
class lynguine.security.access_control.AuditEventType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

Types of audit events.

CREDENTIAL_ACCESS = 'credential_access'
CREDENTIAL_CREATE = 'credential_create'
CREDENTIAL_UPDATE = 'credential_update'
CREDENTIAL_DELETE = 'credential_delete'
ACCESS_DENIED = 'access_denied'
VALIDATION_FAILED = 'validation_failed'
AUTHENTICATION_FAILED = 'authentication_failed'
RATE_LIMIT_EXCEEDED = 'rate_limit_exceeded'
exception lynguine.security.access_control.AccessControlError[source]

Bases: Exception

Base exception for access control errors.

add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception lynguine.security.access_control.AccessDeniedError[source]

Bases: AccessControlError

Raised when access is denied.

add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception lynguine.security.access_control.RateLimitError[source]

Bases: AccessControlError

Raised when rate limit is exceeded.

add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class lynguine.security.access_control.AuditEvent(event_type, credential_key, user=None, context=None, success=True, details=None)[source]

Bases: object

Represents a security audit event.

Initialize an audit event.

Parameters:
  • event_type (AuditEventType) – Type of event

  • credential_key (str) – The credential key involved

  • user (str) – User performing the action

  • context (str) – Context/source of the operation

  • success (bool) – Whether the operation succeeded

  • details (Dict[str, Any]) – Additional event details

to_dict()[source]

Convert event to dictionary.

Returns:

Event as dictionary

Return type:

Dict[str, Any]

to_json()[source]

Convert event to JSON string.

Returns:

Event as JSON

Return type:

str

class lynguine.security.access_control.AuditLogger(log_path=None, enable_console=False, enable_file=True)[source]

Bases: object

Audit logger for credential security events.

Logs security events to structured logs with rotation and tamper detection.

Initialize the audit logger.

Parameters:
  • log_path (str) – Path to audit log file

  • enable_console (bool) – Whether to log to console

  • enable_file (bool) – Whether to log to file

log_event(event)[source]

Log an audit event.

Parameters:

event (AuditEvent) – The audit event to log

Return type:

None

query_events(event_type=None, user=None, start_time=None, end_time=None, limit=100)[source]

Query audit events with filters.

Parameters:
  • event_type (AuditEventType) – Filter by event type

  • user (str) – Filter by user

  • start_time (datetime) – Filter by start time

  • end_time (datetime) – Filter by end time

  • limit (int) – Maximum number of events to return

Returns:

List of matching events

Return type:

List[Dict[str, Any]]

class lynguine.security.access_control.AccessPolicy[source]

Bases: object

Access control policy for credentials.

Defines who can access which credentials with what permissions.

Initialize the access policy.

add_rule(credential_pattern, user_pattern='*', context_pattern='*', access_level=AccessLevel.READ)[source]

Add an access control rule.

Parameters:
  • credential_pattern (str) – Credential key pattern (supports wildcards)

  • user_pattern (str) – User pattern (supports wildcards)

  • context_pattern (str) – Context pattern (supports wildcards)

  • access_level (AccessLevel) – Access level to grant

Return type:

None

check_access(credential_key, operation, user=None, context=None)[source]

Check if access is allowed.

Parameters:
  • credential_key (str) – The credential key

  • operation (AccessLevel) – Required access level

  • user (str) – User requesting access

  • context (str) – Context of the request

Returns:

True if access allowed, False otherwise

Return type:

bool

class lynguine.security.access_control.RateLimiter(max_requests=100, time_window=60)[source]

Bases: object

Rate limiter for credential access operations.

Prevents brute force attacks and excessive credential access.

Initialize the rate limiter.

Parameters:
  • max_requests (int) – Maximum requests per time window

  • time_window (int) – Time window in seconds

check_rate_limit(key, user=None)[source]

Check if request is within rate limit.

Parameters:
  • key (str) – Identifier for rate limiting (e.g., credential key)

  • user (str) – User making the request

Returns:

True if within limit, False otherwise

Return type:

bool

class lynguine.security.access_control.CredentialAccessController(audit_logger=None, access_policy=None, rate_limiter=None)[source]

Bases: object

Integrated access controller for credential operations.

Combines access policy, rate limiting, and audit logging.

Initialize the access controller.

Parameters:
authorize_access(credential_key, operation, user=None, context=None)[source]

Authorize credential access.

Parameters:
  • credential_key (str) – The credential key

  • operation (AccessLevel) – Required access level

  • user (str) – User requesting access

  • context (str) – Context of the request

Raises:
Return type:

None

lynguine.security.access_control.get_access_controller()[source]

Get or create the global access controller.

Returns:

The global access controller

Return type:

CredentialAccessController

lynguine.security.access_control.set_access_controller(controller)[source]

Set a custom global access controller.

Parameters:

controller (CredentialAccessController) – The access controller to use

Return type:

None

Secure Logging

Secure logging and error handling for credential operations.

This module provides utilities to prevent credential leakage in logs and error messages while maintaining useful debugging information.

class lynguine.security.secure_logging.SanitizingFormatter(fmt=None, datefmt=None, style='%', additional_patterns=None)[source]

Bases: Formatter

Logging formatter that sanitizes sensitive information.

This formatter automatically redacts sensitive patterns like API keys, passwords, and tokens from log messages.

Initialize the sanitizing formatter.

Parameters:
  • fmt (str) – Log format string

  • datefmt (str) – Date format string

  • style (str) – Format style (‘%’, ‘{’, or ‘$’)

  • additional_patterns (List[tuple]) – Additional (pattern, replacement) tuples

format(record)[source]

Format log record with sanitization.

Parameters:

record (logging.LogRecord) – Log record to format

Returns:

Formatted and sanitized log message

Return type:

str

sanitize(text)[source]

Sanitize text by removing sensitive patterns.

Parameters:

text (str) – Text to sanitize

Returns:

Sanitized text

Return type:

str

converter()
localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,

tm_sec,tm_wday,tm_yday,tm_isdst)

Convert seconds since the Epoch to a time tuple expressing local time. When ‘seconds’ is not passed in, convert the current time instead.

default_msec_format = '%s,%03d'
default_time_format = '%Y-%m-%d %H:%M:%S'
formatException(ei)

Format and return the specified exception information as a string.

This default implementation just uses traceback.print_exception()

formatMessage(record)
formatStack(stack_info)

This method is provided as an extension point for specialized formatting of stack information.

The input data is a string as returned from a call to traceback.print_stack(), but with the last trailing newline removed.

The base implementation just returns the value passed in.

formatTime(record, datefmt=None)

Return the creation time of the specified LogRecord as formatted text.

This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, an ISO8601-like (or RFC 3339-like) format is used. The resulting string is returned. This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the ‘converter’ attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the ‘converter’ attribute in the Formatter class.

usesTime()

Check if the format uses the creation time of the record.

class lynguine.security.secure_logging.SecureExceptionHandler[source]

Bases: object

Exception handler that sanitizes sensitive information from exceptions.

Initialize the secure exception handler.

sanitize_exception(exc)[source]

Sanitize an exception’s message.

Parameters:

exc (Exception) – The exception to sanitize

Returns:

Exception with sanitized message

Return type:

Exception

sanitize_text(text)[source]

Sanitize text by removing sensitive patterns.

Parameters:

text (str) – Text to sanitize

Returns:

Sanitized text

Return type:

str

sanitize_traceback(tb_str)[source]

Sanitize a traceback string.

Parameters:

tb_str (str) – Traceback string

Returns:

Sanitized traceback

Return type:

str

format_exception(exc_type, exc_value, exc_traceback)[source]

Format an exception with sanitized information.

Parameters:
  • exc_type (type) – Exception type

  • exc_value (Exception) – Exception instance

  • exc_traceback (Any) – Exception traceback

Returns:

Formatted and sanitized exception

Return type:

str

lynguine.security.secure_logging.setup_secure_logging(logger=None, level=20, format_string=None, additional_patterns=None)[source]

Set up secure logging with sanitization for a logger.

Parameters:
  • logger (logging.Logger) – Logger to configure (None for root logger)

  • level (int) – Logging level

  • format_string (str) – Custom format string

  • additional_patterns (List[tuple]) – Additional sanitization patterns

Returns:

Configured logger

Return type:

logging.Logger

lynguine.security.secure_logging.sanitize_dict(data, sensitive_keys=None)[source]

Sanitize a dictionary by redacting sensitive keys.

Parameters:
  • data (Dict[str, Any]) – Dictionary to sanitize

  • sensitive_keys (List[str]) – List of keys to redact (case-insensitive)

Returns:

Sanitized dictionary

Return type:

Dict[str, Any]

lynguine.security.secure_logging.secure_repr(obj, max_len=100)[source]

Get a secure string representation of an object.

This function attempts to sanitize the repr() output to avoid exposing sensitive information.

Parameters:
  • obj (Any) – Object to represent

  • max_len (int) – Maximum length of representation

Returns:

Secure representation

Return type:

str

class lynguine.security.secure_logging.SecureLogger(name, logger=None)[source]

Bases: object

Wrapper around standard logger with automatic sanitization.

Initialize secure logger.

Parameters:
  • name (str) – Logger name

  • logger (logging.Logger) – Underlying logger (creates new if None)

debug(msg, *args, **kwargs)[source]

Log debug message with sanitization.

Parameters:

msg (str)

info(msg, *args, **kwargs)[source]

Log info message with sanitization.

Parameters:

msg (str)

warning(msg, *args, **kwargs)[source]

Log warning message with sanitization.

Parameters:

msg (str)

error(msg, *args, **kwargs)[source]

Log error message with sanitization.

Parameters:

msg (str)

critical(msg, *args, **kwargs)[source]

Log critical message with sanitization.

Parameters:

msg (str)

exception(msg, *args, **kwargs)[source]

Log exception with sanitized traceback.

Parameters:

msg (str)

lynguine.security.secure_logging.get_secure_logger(name)[source]

Get or create a secure logger.

Parameters:

name (str) – Logger name

Returns:

Secure logger instance

Return type:

SecureLogger

Migration Tools

Migration tools for transitioning to secure credential management.

This module provides utilities to migrate existing credential configurations to the new secure credential management system.

exception lynguine.security.migration.MigrationError[source]

Bases: Exception

Exception raised during migration.

add_note()

Exception.add_note(note) – add a note to the exception

args
with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class lynguine.security.migration.CredentialMigrator(credential_manager=None, backup_dir=None)[source]

Bases: object

Tool for migrating credentials to secure storage.

This class helps migrate from: - Plain text configuration files - Environment variables (documentation only) - Legacy credential storage

To the new secure credential management system.

Initialize the credential migrator.

Parameters:
  • credential_manager (CredentialManager) – Credential manager to use (uses global if None)

  • backup_dir (str) – Directory for backups

backup_file(file_path)[source]

Create a backup of a file before migration.

Parameters:

file_path (str) – Path to file to backup

Returns:

Path to backup file

Return type:

str

migrate_yaml_config(config_file, credential_mappings, dry_run=False)[source]

Migrate credentials from a YAML configuration file.

Parameters:
  • config_file (str) – Path to YAML configuration file

  • credential_mappings (Dict[str, str]) – Map of config keys to credential names

  • dry_run (bool) – If True, don’t make changes (default: False)

Returns:

Migration report

Return type:

Dict[str, Any]

migrate_google_sheets_credentials(config_file, credential_name='google_sheets_oauth', dry_run=False)[source]

Migrate Google Sheets credentials specifically.

Parameters:
  • config_file (str) – Path to configuration file

  • credential_name (str) – Name for the credential in secure storage

  • dry_run (bool) – If True, don’t make changes

Returns:

Migration report

Return type:

Dict[str, Any]

generate_environment_variable_script(credentials, output_file=None, shell='bash')[source]

Generate a shell script to set environment variables for credentials.

Parameters:
  • credentials (Dict[str, Dict[str, Any]]) – Dictionary of credential_name -> credential_value

  • output_file (str) – Path to output script (optional)

  • shell (str) – Shell type (“bash” or “fish”)

Returns:

Script content

Return type:

str

validate_migration(config_file)[source]

Validate that a migrated configuration works correctly.

Parameters:

config_file (str) – Path to configuration file

Returns:

Validation report

Return type:

Dict[str, Any]

rollback(backup_path)[source]

Rollback a migration by restoring from backup.

Parameters:

backup_path (str) – Path to backup file

Return type:

None

lynguine.security.migration.create_migration_guide()[source]

Create a migration guide document.

Returns:

Migration guide text

Return type:

str

lynguine.security.migration.save_migration_guide(output_file=None)[source]

Save the migration guide to a file.

Parameters:

output_file (str) – Path to output file (optional)

Returns:

Path to saved file

Return type:

str

Quick Reference

Core Functions

from lynguine.security import (
    get_credential,           # Get a credential
    set_credential,           # Store a credential
    delete_credential,        # Remove a credential
    list_credentials,         # List all credentials
    get_credential_manager,   # Get manager instance
    get_access_controller,    # Get access controller
)

Providers

from lynguine.security import (
    EnvironmentCredentialProvider,     # Environment variables
    EncryptedFileCredentialProvider,   # Encrypted files
    CredentialProvider,                # Base class for custom providers
)

Access Control

from lynguine.security import (
    AccessLevel,              # Access level enum
    AccessPolicy,             # Access control policy
    RateLimiter,             # Rate limiting
    CredentialAccessController,  # Unified access control
)

Exceptions

from lynguine.security import (
    CredentialError,              # Base exception
    CredentialNotFoundError,      # Credential missing
    CredentialValidationError,    # Invalid credential
    CredentialEncryptionError,    # Encryption failed
    AccessDeniedError,            # Access denied
    RateLimitError,              # Rate limit exceeded
)

Logging

from lynguine.security import (
    SecureLogger,            # Secure logging wrapper
    SanitizingFormatter,     # Log sanitization
    SecureExceptionHandler,  # Exception sanitization
)

Migration

from lynguine.security.migration import (
    CredentialMigrator,      # Migration tool
)

Examples

Basic Usage

from lynguine.security import get_credential, set_credential

# Store a credential
set_credential("my_api_key", {
    "key": "secret123",
    "endpoint": "https://api.example.com"
})

# Retrieve a credential
creds = get_credential("my_api_key")
api_key = creds["value"]["key"]

Environment Variables

# Set credential as environment variable
export LYNGUINE_CRED_MY_KEY='{"api_key":"secret","endpoint":"https://api.example.com"}'
from lynguine.security import get_credential

# Automatically retrieved from environment
creds = get_credential("MY_KEY")

Encrypted Storage

import os
from lynguine.security import set_credential

# Set master key
os.environ["LYNGUINE_MASTER_KEY"] = "your-secure-password"

# Store encrypted credential
set_credential("google_sheets", {
    "client_id": "...",
    "client_secret": "..."
})

Access Control

from lynguine.security import (
    get_access_controller,
    AccessPolicy,
    AccessLevel
)

controller = get_access_controller()
policy = AccessPolicy()

# Add access rule
policy.add_rule(
    credential_pattern="prod_*",
    user_pattern="admin",
    access_level=AccessLevel.ADMIN
)

controller.set_policy(policy)

Error Handling

from lynguine.security import (
    get_credential,
    CredentialNotFoundError
)

try:
    creds = get_credential("my_key")
except CredentialNotFoundError:
    print("Credential not found - please configure MY_KEY")
    # Handle missing credential

See Also