Skip to content

Configurable authentication method selection for Neo4j compatibility #61

@rysweet

Description

@rysweet

Description

Following the code review for PR #57, implement configurable authentication method selection to provide more control over Neo4j authentication compatibility modes.

Current Behavior

The Neo4jManager currently uses an automatic fallback mechanism:

  1. First attempts Neo4j 5.x basic_auth() format
  2. Falls back to Neo4j 4.x tuple format if specific errors occur
  3. No user control over authentication method selection

Proposed Enhancement

1. Authentication Mode Configuration

Add explicit configuration options for authentication method selection:

from enum import Enum

class AuthMethod(Enum):
    AUTO = "auto"           # Current behavior - try 5.x, fallback to 4.x
    BASIC_AUTH = "basic"    # Force Neo4j 5.x basic_auth() only
    TUPLE_AUTH = "tuple"    # Force Neo4j 4.x tuple format only
    PREFER_BASIC = "prefer_basic"  # Try basic_auth first, fallback to tuple
    PREFER_TUPLE = "prefer_tuple"  # Try tuple first, fallback to basic_auth

class Neo4jManager:
    def __init__(self, auth_method: AuthMethod = AuthMethod.AUTO, ...):
        self.auth_method = auth_method

2. Configuration Sources

Support multiple configuration methods:

Constructor Parameter

manager = Neo4jManager(auth_method=AuthMethod.BASIC_AUTH)

Environment Variable

export NEO4J_AUTH_METHOD=basic
export NEO4J_AUTH_METHOD=tuple  
export NEO4J_AUTH_METHOD=auto

Configuration File Support

# Support for config file or dict-based configuration
config = {
    "neo4j": {
        "auth_method": "basic",
        "fallback_enabled": True
    }
}

3. Logging and Diagnostics

Enhanced logging to track authentication method selection:

logger.info(f"Using authentication method: {self.auth_method.value}")
logger.info(f"Neo4j authentication successful using {selected_method} method")

4. Validation and Error Handling

  • Validate authentication method configuration
  • Provide clear error messages for incompatible settings
  • Log authentication method decisions for troubleshooting

Use Cases

1. Environment-Specific Configuration

  • Development: Use AUTO for maximum compatibility
  • Production Neo4j 5.x: Use BASIC_AUTH for optimal performance
  • Legacy Neo4j 4.x: Use TUPLE_AUTH to avoid unnecessary retry attempts

2. Performance Optimization

  • Eliminate authentication retry overhead when server version is known
  • Reduce connection establishment time in homogeneous environments

3. Troubleshooting and Debugging

  • Force specific authentication methods to isolate compatibility issues
  • Test authentication behavior across different Neo4j versions

Technical Implementation

1. Authentication Strategy Pattern

class AuthStrategy:
    def authenticate(self, uri, user, password, max_connections):
        raise NotImplementedError

class BasicAuthStrategy(AuthStrategy):
    def authenticate(self, uri, user, password, max_connections):
        return GraphDatabase.driver(uri, auth=basic_auth(user, password), ...)

class TupleAuthStrategy(AuthStrategy):
    def authenticate(self, uri, user, password, max_connections):
        return GraphDatabase.driver(uri, auth=(user, password), ...)

2. Method Selection Logic

def _get_auth_strategies(self) -> List[AuthStrategy]:
    if self.auth_method == AuthMethod.BASIC_AUTH:
        return [BasicAuthStrategy()]
    elif self.auth_method == AuthMethod.TUPLE_AUTH:
        return [TupleAuthStrategy()]
    elif self.auth_method == AuthMethod.AUTO:
        return [BasicAuthStrategy(), TupleAuthStrategy()]
    # ... handle other modes

3. Configuration Validation

  • Validate authentication method enum values
  • Warn about deprecated or problematic configurations
  • Provide migration guidance for configuration changes

Backward Compatibility

  • Default behavior remains unchanged (AUTO mode)
  • All existing code continues to work without modification
  • New configuration options are purely additive

Acceptance Criteria

  • AuthMethod enum with all specified options
  • Constructor parameter for authentication method selection
  • Environment variable support (NEO4J_AUTH_METHOD)
  • Configuration file/dict support
  • Enhanced logging for authentication method selection
  • Comprehensive validation and error handling
  • Performance benchmarks for different authentication modes
  • Unit tests covering all authentication method scenarios
  • Documentation with configuration examples
  • Migration guide for existing deployments

Future Enhancements

  • Support for custom authentication strategies
  • Integration with configuration management systems
  • Authentication method auto-detection based on server version
  • Metrics and monitoring for authentication method usage

This enhancement provides users with fine-grained control over Neo4j authentication while maintaining the robust fallback behavior for compatibility.

Generated following code review feedback for PR #57.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions