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:
ABCAbstract 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:
- 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
- class lynguine.security.EnvironmentCredentialProvider(prefix='LYNGUINE_CRED', name=None)[source]
Bases:
CredentialProviderCredential 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:
- 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.
- delete_credential(key, **kwargs)[source]
Delete a credential from environment variables (current process only).
- Parameters:
key (str) – The credential key/identifier
- Return type:
None
- class lynguine.security.EncryptedFileCredentialProvider(storage_path=None, master_key=None, name=None)[source]
Bases:
CredentialProviderCredential 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:
- Raises:
CredentialEncryptionError – If cryptography is not available
- delete_credential(key, **kwargs)[source]
Delete a credential file.
- Parameters:
key (str) – The credential key/identifier
- Return type:
None
- class lynguine.security.CredentialManager(providers=None, cache_ttl=300, enable_cache=True)[source]
Bases:
objectCentral 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:
- Returns:
The credential data or None if not found
- Return type:
Optional[Dict[str, Any]]
- Raises:
CredentialNotFoundError – If credential not found in any provider
CredentialValidationError – If credential validation fails
- set_credential(key, value, provider_name=None, credential_type=None, **kwargs)[source]
Store a credential using a specific provider.
- Parameters:
- Raises:
CredentialValidationError – If validation fails
CredentialError – If storage fails
- Return type:
None
- lynguine.security.get_credential_manager()[source]
Get or create the global credential manager instance.
- Returns:
The global credential manager
- Return type:
- 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.
- lynguine.security.set_credential(key, value, credential_type=None)[source]
Set a credential using the global credential manager.
- exception lynguine.security.CredentialError[source]
Bases:
ExceptionBase 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:
CredentialErrorRaised 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:
CredentialErrorRaised 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:
CredentialErrorRaised 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:
objectThread-safe cache for credentials with TTL support.
Initialize the credential cache.
- Parameters:
default_ttl (int) – Default time-to-live in seconds
- class lynguine.security.AccessLevel(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]
Bases:
EnumAccess 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:
EnumTypes 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:
objectRepresents a security audit event.
Initialize an audit event.
- Parameters:
- class lynguine.security.AuditLogger(log_path=None, enable_console=False, enable_file=True)[source]
Bases:
objectAudit logger for credential security events.
Logs security events to structured logs with rotation and tamper detection.
Initialize the audit logger.
- Parameters:
- 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:
objectAccess 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:
- class lynguine.security.RateLimiter(max_requests=100, time_window=60)[source]
Bases:
objectRate limiter for credential access operations.
Prevents brute force attacks and excessive credential access.
Initialize the rate limiter.
- Parameters:
- class lynguine.security.CredentialAccessController(audit_logger=None, access_policy=None, rate_limiter=None)[source]
Bases:
objectIntegrated access controller for credential operations.
Combines access policy, rate limiting, and audit logging.
Initialize the access controller.
- Parameters:
audit_logger (AuditLogger) – Audit logger instance
access_policy (AccessPolicy) – Access policy instance
rate_limiter (RateLimiter) – Rate limiter instance
- 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:
AccessDeniedError – If access is denied
RateLimitError – If rate limit is exceeded
- Return type:
None
- lynguine.security.get_access_controller()[source]
Get or create the global access controller.
- Returns:
The global access controller
- Return type:
- 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:
ExceptionBase 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:
AccessControlErrorRaised 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:
AccessControlErrorRaised 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:
FormatterLogging 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:
- format(record)[source]
Format log record with sanitization.
- Parameters:
record (logging.LogRecord) – Log record to format
- Returns:
Formatted and sanitized log message
- Return type:
- 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:
objectException handler that sanitizes sensitive information from exceptions.
Initialize the secure exception handler.
- class lynguine.security.SecureLogger(name, logger=None)[source]
Bases:
objectWrapper around standard logger with automatic sanitization.
Initialize secure logger.
- Parameters:
name (str) – Logger name
logger (logging.Logger) – Underlying logger (creates new if None)
- 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:
- lynguine.security.get_secure_logger(name)[source]
Get or create a secure logger.
- Parameters:
name (str) – Logger name
- Returns:
Secure logger instance
- Return type:
- lynguine.security.sanitize_dict(data, sensitive_keys=None)[source]
Sanitize a dictionary by redacting sensitive keys.
- 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.
- class lynguine.security.CredentialMigrator(credential_manager=None, backup_dir=None)[source]
Bases:
objectTool 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
- migrate_yaml_config(config_file, credential_mappings, dry_run=False)[source]
Migrate credentials from a YAML configuration file.
- migrate_google_sheets_credentials(config_file, credential_name='google_sheets_oauth', dry_run=False)[source]
Migrate Google Sheets credentials specifically.
- generate_environment_variable_script(credentials, output_file=None, shell='bash')[source]
Generate a shell script to set environment variables for credentials.
- exception lynguine.security.MigrationError[source]
Bases:
ExceptionException 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.
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:
ExceptionBase 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:
CredentialErrorRaised 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:
CredentialErrorRaised 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:
CredentialErrorRaised 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:
ABCAbstract 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:
- 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
- class lynguine.security.credentials.EnvironmentCredentialProvider(prefix='LYNGUINE_CRED', name=None)[source]
Bases:
CredentialProviderCredential 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:
- 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.
- delete_credential(key, **kwargs)[source]
Delete a credential from environment variables (current process only).
- Parameters:
key (str) – The credential key/identifier
- Return type:
None
- class lynguine.security.credentials.EncryptedFileCredentialProvider(storage_path=None, master_key=None, name=None)[source]
Bases:
CredentialProviderCredential 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:
- Raises:
CredentialEncryptionError – If cryptography is not available
- delete_credential(key, **kwargs)[source]
Delete a credential file.
- Parameters:
key (str) – The credential key/identifier
- Return type:
None
- class lynguine.security.credentials.CredentialCache(default_ttl=300)[source]
Bases:
objectThread-safe cache for credentials with TTL support.
Initialize the credential cache.
- Parameters:
default_ttl (int) – Default time-to-live in seconds
- class lynguine.security.credentials.CredentialManager(providers=None, cache_ttl=300, enable_cache=True)[source]
Bases:
objectCentral 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:
- Returns:
The credential data or None if not found
- Return type:
Optional[Dict[str, Any]]
- Raises:
CredentialNotFoundError – If credential not found in any provider
CredentialValidationError – If credential validation fails
- set_credential(key, value, provider_name=None, credential_type=None, **kwargs)[source]
Store a credential using a specific provider.
- Parameters:
- Raises:
CredentialValidationError – If validation fails
CredentialError – If storage fails
- Return type:
None
- lynguine.security.credentials.get_credential_manager()[source]
Get or create the global credential manager instance.
- Returns:
The global credential manager
- Return type:
- 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.
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:
EnumAccess 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:
EnumTypes 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:
ExceptionBase 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:
AccessControlErrorRaised 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:
AccessControlErrorRaised 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:
objectRepresents a security audit event.
Initialize an audit event.
- Parameters:
- class lynguine.security.access_control.AuditLogger(log_path=None, enable_console=False, enable_file=True)[source]
Bases:
objectAudit logger for credential security events.
Logs security events to structured logs with rotation and tamper detection.
Initialize the audit logger.
- Parameters:
- 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:
objectAccess 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:
- class lynguine.security.access_control.RateLimiter(max_requests=100, time_window=60)[source]
Bases:
objectRate limiter for credential access operations.
Prevents brute force attacks and excessive credential access.
Initialize the rate limiter.
- Parameters:
- class lynguine.security.access_control.CredentialAccessController(audit_logger=None, access_policy=None, rate_limiter=None)[source]
Bases:
objectIntegrated access controller for credential operations.
Combines access policy, rate limiting, and audit logging.
Initialize the access controller.
- Parameters:
audit_logger (AuditLogger) – Audit logger instance
access_policy (AccessPolicy) – Access policy instance
rate_limiter (RateLimiter) – Rate limiter instance
- 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:
AccessDeniedError – If access is denied
RateLimitError – If rate limit is exceeded
- 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:
- 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:
FormatterLogging 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:
- format(record)[source]
Format log record with sanitization.
- Parameters:
record (logging.LogRecord) – Log record to format
- Returns:
Formatted and sanitized log message
- Return type:
- 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:
objectException handler that sanitizes sensitive information from exceptions.
Initialize the secure exception handler.
- 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:
- lynguine.security.secure_logging.sanitize_dict(data, sensitive_keys=None)[source]
Sanitize a dictionary by redacting sensitive keys.
- 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.
- class lynguine.security.secure_logging.SecureLogger(name, logger=None)[source]
Bases:
objectWrapper around standard logger with automatic sanitization.
Initialize secure logger.
- Parameters:
name (str) – Logger name
logger (logging.Logger) – Underlying logger (creates new if None)
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:
ExceptionException 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:
objectTool 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
- migrate_yaml_config(config_file, credential_mappings, dry_run=False)[source]
Migrate credentials from a YAML configuration file.
- migrate_google_sheets_credentials(config_file, credential_name='google_sheets_oauth', dry_run=False)[source]
Migrate Google Sheets credentials specifically.
- generate_environment_variable_script(credentials, output_file=None, shell='bash')[source]
Generate a shell script to set environment variables for credentials.
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
User Guide - Complete user guide with step-by-step instructions
Implementation Summary - Technical implementation details
Security - Security documentation overview