# Secure Credential Management


Treasury Analytics Core provides multiple secure options for managing database credentials, now enhanced with centralized settings and password expiration tracking.

## Recommended Approach: EngineFactory with Auto Auth

The simplest and most reliable method is to use the `EngineFactory` with automatic authentication:

``` python
from nova_fde.core.engine_factory import EngineFactory

# Create engine with automatic credential handling and password expiration checks
engine = EngineFactory.create_with_auto_auth(
    project_root="./my_project",
    check_password_expiry=True
)
```

This approach will automatically: 1. Check for global database settings 2. Verify password expiration status and warn if needed 3. Check for credentials in environment variables 4. Look in the system keyring (Keychain, Credential Manager, SecretService) 5. Search for stored credentials in the user’s home directory 6. Fall back to prompting the user if needed 7. Save entered credentials securely for future use

## Using System Keyring

A secure method is to use your system’s secure credential store:

- **macOS**: Keychain
- **Windows**: Credential Manager
- **Linux**: SecretService/KWallet

### Setting Up Credentials in Keyring

You can set up credentials using the included setup tools:

``` bash
# Interactive setup helper
python -m nova_fde.utils.setup_helper

# OR dedicated configuration tool
python -m nova_fde.scripts.configure_db --keyring-only
```

### Using Keyring in Your Code

Once credentials are stored in your system keyring, you can use them in code:

``` python
from nova_fde import FinanceDataEngine
from nova_fde.utils import setup_logging

# Set up logging
logger, console = setup_logging()

# Initialize with credentials from keyring
engine = FinanceDataEngine(
    console=console,
    use_keyring=True,
    keyring_service="nova_fde"
)
```

## Using Private Credential Directories

For environments where keyring isn’t available, you can store credentials in a private directory:

``` python
from nova_fde import FinanceDataEngine

# Initialize with credentials from a private directory
engine = FinanceDataEngine(
    credential_path="C:/Users/username/private/credentials"
)
```

To set up a credential file in a private directory:

``` bash
# Create a credentials file in a private directory
python -m nova_fde.scripts.configure_db --path /path/to/private/directory
```

## Using Settings Factory

For more advanced configuration, use the settings factory:

``` python
from nova_fde import FinanceDataEngine
from nova_fde.config.settings_factory import SettingsFactory

# Create settings from keyring
settings = SettingsFactory.from_keyring()

# Or from a credential path
settings = SettingsFactory.from_credential_path("/path/to/credentials")

# Or with global database settings
from nova_fde.core.engine_factory import GlobalSettings
global_settings = GlobalSettings()
db_settings = global_settings.get_db_settings()

# Initialize engine with settings
engine = FinanceDataEngine(settings=settings)
```

## Password Expiration Management

Treasury Analytics Core now includes password expiration tracking to ensure database passwords are rotated regularly:

### Recording a Password Update

When you update your database password, record it to start tracking expiration:

``` bash
python -m nova_fde.scripts.manage_settings --update-password
```

### Checking Password Expiration

Check the status of your password expiration:

``` bash
python -m nova_fde.scripts.manage_settings --check
```

### Creating a Calendar Reminder

Create a calendar reminder file for password rotation:

``` bash
python -m nova_fde.scripts.manage_settings --create-reminder
```

For more information about password management, see the [Global Settings & Password Management](global_settings.qmd) documentation.

## Direct Credential Management

You can also directly use the `CredentialManager` class for more control:

``` python
from nova_fde.utils.credentials import CredentialManager

# Create credential manager
cred_mgr = CredentialManager(service_name="nova_fde")

# Store credentials
cred_mgr.store_credentials("username", "password")

# Retrieve credentials
username, password = cred_mgr.get_credentials()

# Clear credentials
cred_mgr.clear_credentials()
```

## Command-Line Configuration

The `configure_db` script provides a command-line interface for setting up database credentials:

``` bash
# Store credentials in keyring and create .env file
python -m nova_fde.scripts.configure_db --path ./my_project

# Store credentials in keyring only
python -m nova_fde.scripts.configure_db --keyring-only

# Specify a custom keyring service name
python -m nova_fde.scripts.configure_db --service my_service_name
```

## Credential Validation

The `CredentialManager` provides methods to validate credentials:

``` python
from nova_fde.utils.credentials import CredentialManager
from sqlalchemy import create_engine, text

# Create credential manager
cred_mgr = CredentialManager(service_name="nova_fde")

# Define a function to test the connection
def test_connection(username, password):
    try:
        # Create a connection string
        conn_str = f"postgresql://{username}:{password}@your_host:5432/your_db"
        
        # Create engine and test connection
        engine = create_engine(conn_str)
        with engine.connect() as conn:
            result = conn.execute(text("SELECT 1")).fetchone()
            return result[0] == 1
    except Exception:
        return False

# Validate credentials with connection test
valid = cred_mgr.validate_connection(
    connection_func=test_connection,
    max_attempts=3,
    verbose=True
)

if valid:
    print("Connection successful!")
else:
    print("Could not establish connection with provided credentials")
```

## First-Time Setup

For new users, the setup helper provides a guided setup experience:

``` bash
python -m nova_fde.utils.setup_helper
```

This interactive tool will:

1.  Ask about credential storage preferences
2.  Collect database connection information
3.  Store credentials securely in the system keyring
4.  Optionally create a minimal .env file without the password
5.  Offer to set up global settings for database configuration

## Integration with Global Settings

When using global settings, you only need to store username and password credentials - other database connection details come from the centralized configuration:

1.  First set up your global settings:

    ``` bash
    python -m nova_fde.scripts.manage_settings --create \
      --db-host=your-server.example.com \
      --db-port=5432 \
      --db-name=your_database
    ```

2.  Then store just your credentials:

    ``` bash
    python -m nova_fde.scripts.configure_db --keyring-only
    ```

3.  Use both in your code:

    ``` python
    engine = EngineFactory.create_with_auto_auth(
        project_root="./my_project",
        check_password_expiry=True
    )
    ```

This approach provides the best security and maintainability by separating database connection details from credentials.
