Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,45 @@
import time
from typing import Any, Dict, Optional, Union

from azure.core.exceptions import ClientAuthenticationError
from azure.identity import DefaultAzureCredential
from call_processing.log.logger import logger

from redis import Connection
from redis import ConnectionError
from redis import ConnectionPool
from redis import Redis
from redis import RedisError
from redis import SSLConnection
from redis import TimeoutError
from redis.credentials import CredentialProvider
from tenacity import retry
from tenacity import retry_if_exception_type
from tenacity import stop_after_attempt
from tenacity import wait_exponential


class AzureManagedRedisProvider(CredentialProvider):
"""
Adapter to bridge Azure Identity with Redis CredentialProvider.
Azure Managed Redis requires 'default' as the username and the
Entra ID access token as the password.
"""

def __init__(self):
self.credential = DefaultAzureCredential()
self.scope = 'https://redis.azure.com/.default'
self.username = os.getenv('REDIS_USERNAME', 'default')

def get_credentials(self):
try:
token = self.credential.get_token(self.scope)
return (self.username, token.token)
except ClientAuthenticationError as e:
logger.error(f'Azure authentication failed: {e}')
raise


class CacheManager:
def __init__(
self,
Expand Down Expand Up @@ -51,19 +77,41 @@ def _create_connection_pool(
pool_size: int,
) -> ConnectionPool:
try:
return ConnectionPool(
host=str(os.getenv('REDIS_HOST', 'localhost')),
port=int(os.getenv('REDIS_PORT', 6379)),
db=int(os.getenv('REDIS_DB', 0)),
max_connections=pool_size,
socket_timeout=socket_timeout,
socket_keepalive=socket_keepalive,
socket_connect_timeout=connection_timeout,
retry_on_timeout=True,
health_check_interval=30,
encoding='utf-8',
decode_responses=True,
)
host = os.getenv('REDIS_HOST', 'localhost')
port = int(os.getenv('REDIS_PORT', 6379))
protocol = os.getenv('REDIS_PROTOCOL', 'redis')
password = os.getenv('REDIS_PASSWORD')
cloud_provider = os.getenv('CLOUD_PROVIDER', '').lower()

connection_class = Connection
if protocol == 'rediss' or port == 10000:
logger.info(f'Using SSLConnection for Redis (Port: {port})')
connection_class = SSLConnection

pool_kwargs = {
'connection_class': connection_class,
'host': host,
'port': port,
'db': int(os.getenv('REDIS_DB', 0)),
'max_connections': pool_size,
'socket_timeout': socket_timeout,
'socket_keepalive': socket_keepalive,
'socket_connect_timeout': connection_timeout,
'retry_on_timeout': True,
'health_check_interval': 30,
'encoding': 'utf-8',
'decode_responses': True,
}

if cloud_provider == 'azure' and not password:
logger.info(
'Configuring Azure Entra ID (Workload Identity) authentication'
)
pool_kwargs['credential_provider'] = AzureManagedRedisProvider()
elif password:
pool_kwargs['password'] = password

Comment on lines +106 to +113

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Silent fallback to unauthenticated Redis when credentials are misconfigured.

When CLOUD_PROVIDER is not azure and REDIS_PASSWORD is unset, the pool is created without any authentication. This may be intentional for local development, but in production it risks connecting to Redis without auth if environment variables are misconfigured.

Consider adding a warning log or, for non-local environments, requiring explicit opt-in for unauthenticated connections:

🛡️ Suggested improvement
             if cloud_provider == 'azure' and not password:
                 logger.info(
                     'Configuring Azure Entra ID (Workload Identity) authentication'
                 )
                 pool_kwargs['credential_provider'] = AzureManagedRedisProvider()
             elif password:
                 pool_kwargs['password'] = password
+            else:
+                logger.warning(
+                    'No Redis authentication configured. '
+                    'Set REDIS_PASSWORD or use CLOUD_PROVIDER=azure for managed identity.'
+                )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@wavefront/server/apps/call_processing/call_processing/cache/cache_manager.py`
around lines 105 - 112, The current branch silently creates an unauthenticated
Redis pool when cloud_provider != 'azure' and password is falsy; update the
logic around the pool_kwargs assignment (the block referencing cloud_provider,
password, pool_kwargs and AzureManagedRedisProvider) to either (a) log a clear
warning via logger.warning when running in non-local/non-debug modes that Redis
will be created without authentication, or (b) require an explicit opt-in
environment flag (e.g., ALLOW_UNAUTHENTICATED_REDIS or a check against
settings.DEBUG/ENVIRONMENT) before allowing omission of pool_kwargs['password'];
implement the chosen approach by adding a conditional guard and warning/error
log so production misconfiguration is visible and only permit unauthenticated
connections when the opt-in flag is present.

return ConnectionPool(**pool_kwargs)
except Exception as e:
logger.error(f'Failed to create connection pool: {e}s')
raise
Expand Down
1 change: 1 addition & 0 deletions wavefront/server/apps/call_processing/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ dependencies = [
"httpx>=0.27.0",
# Redis and caching
"redis>=5.0.0",
"azure-identity>=1.17.0,<2.0.0",
"tenacity>=8.0.0",
# Pipecat and voice processing
"pipecat-ai[websocket,cartesia,google,silero,deepgram,groq,runner,azure,local-smart-turn-v3,sarvam,tracing]==0.0.103",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,45 @@
import time
from typing import Any, List, Optional, Union

from azure.core.exceptions import ClientAuthenticationError
from azure.identity import DefaultAzureCredential
from common_module.common_cache import CommonCache
from common_module.log.logger import logger
from redis import Connection
from redis import ConnectionError
from redis import ConnectionPool
from redis import Redis
from redis import RedisError
from redis import SSLConnection
from redis import TimeoutError
from redis.credentials import CredentialProvider
from tenacity import retry
from tenacity import retry_if_exception_type
from tenacity import stop_after_attempt
from tenacity import wait_exponential


class AzureManagedRedisProvider(CredentialProvider):
"""
Adapter to bridge Azure Identity with Redis CredentialProvider.
Azure Managed Redis requires 'default' as the username and the
Entra ID access token as the password.
"""

def __init__(self):
self.credential = DefaultAzureCredential()
self.scope = 'https://redis.azure.com/.default'
self.username = os.getenv('REDIS_USERNAME', 'default')

def get_credentials(self):
try:
token = self.credential.get_token(self.scope)
return (self.username, token.token)
except ClientAuthenticationError as e:
logger.error(f'Azure authentication failed: {e}')
raise


class CacheManager(CommonCache):
def __init__(
self,
Expand Down Expand Up @@ -58,19 +84,41 @@ def _create_connection_pool(
pool_size: int,
) -> ConnectionPool:
try:
return ConnectionPool(
host=str(os.getenv('REDIS_HOST', 'localhost')),
port=int(os.getenv('REDIS_PORT', 6379)),
db=int(os.getenv('REDIS_DB', 0)),
max_connections=pool_size,
socket_timeout=socket_timeout,
socket_keepalive=socket_keepalive,
socket_connect_timeout=connection_timeout,
retry_on_timeout=True,
health_check_interval=30,
encoding='utf-8',
decode_responses=True,
)
host = os.getenv('REDIS_HOST', 'localhost')
port = int(os.getenv('REDIS_PORT', 6379))
protocol = os.getenv('REDIS_PROTOCOL', 'redis')
password = os.getenv('REDIS_PASSWORD')
cloud_provider = os.getenv('CLOUD_PROVIDER', '').lower()

connection_class = Connection
if protocol == 'rediss' or port == 10000:
logger.info(f'Using SSLConnection for Redis (Port: {port})')
connection_class = SSLConnection

pool_kwargs = {
'connection_class': connection_class,
'host': host,
'port': port,
'db': int(os.getenv('REDIS_DB', 0)),
'max_connections': pool_size,
'socket_timeout': socket_timeout,
'socket_keepalive': socket_keepalive,
'socket_connect_timeout': connection_timeout,
'retry_on_timeout': True,
'health_check_interval': 30,
'encoding': 'utf-8',
'decode_responses': True,
}

if cloud_provider == 'azure' and not password:
logger.info(
'Configuring Azure Entra ID (Workload Identity) authentication'
)
pool_kwargs['credential_provider'] = AzureManagedRedisProvider()
elif password:
pool_kwargs['password'] = password
Comment on lines +113 to +119

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Silent fallback to unauthenticated Redis when credentials are misconfigured.

Same concern as the call_processing module - when CLOUD_PROVIDER is not azure and REDIS_PASSWORD is unset, no authentication is configured. A warning log would help surface misconfigurations.

🛡️ Suggested improvement
             if cloud_provider == 'azure' and not password:
                 logger.info(
                     'Configuring Azure Entra ID (Workload Identity) authentication'
                 )
                 pool_kwargs['credential_provider'] = AzureManagedRedisProvider()
             elif password:
                 pool_kwargs['password'] = password
+            else:
+                logger.warning(
+                    'No Redis authentication configured. '
+                    'Set REDIS_PASSWORD or use CLOUD_PROVIDER=azure for managed identity.'
+                )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if cloud_provider == 'azure' and not password:
logger.info(
'Configuring Azure Entra ID (Workload Identity) authentication'
)
pool_kwargs['credential_provider'] = AzureManagedRedisProvider()
elif password:
pool_kwargs['password'] = password
if cloud_provider == 'azure' and not password:
logger.info(
'Configuring Azure Entra ID (Workload Identity) authentication'
)
pool_kwargs['credential_provider'] = AzureManagedRedisProvider()
elif password:
pool_kwargs['password'] = password
else:
logger.warning(
'No Redis authentication configured. '
'Set REDIS_PASSWORD or use CLOUD_PROVIDER=azure for managed identity.'
)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@wavefront/server/modules/db_repo_module/db_repo_module/cache/cache_manager.py`
around lines 112 - 118, The code silently falls back to unauthenticated Redis
when cloud_provider != 'azure' and password is falsy; update cache_manager.py to
detect this condition and emit a warning log so misconfigured REDIS_PASSWORD is
visible: inside the block handling pool_kwargs (referencing cloud_provider,
password, pool_kwargs and AzureManagedRedisProvider) add a logger.warn/info
message when password is not provided for non-azure providers, and ensure that
when cloud_provider == 'azure' we still use AzureManagedRedisProvider as before;
keep existing behavior but surface the missing credentials via a clear log
message.


return ConnectionPool(**pool_kwargs)
except Exception as e:
logger.error(f'Failed to create connection pool: {e}s')
raise
Expand Down
1 change: 1 addition & 0 deletions wavefront/server/modules/db_repo_module/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ dependencies = [
"sqlalchemy>=2.0.36,<3.0.0",
"alembic>=1.14.1,<2.0.0",
"redis>=5.2.1,<6.0.0",
"azure-identity>=1.17.0,<2.0.0",
"pgvector>=0.4.1",
"tenacity>=8.1.0,<9.0.0",
"psycopg[binary,pool]>=3.2.3,<4.0.0",
Expand Down
4 changes: 4 additions & 0 deletions wavefront/server/uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading