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
2 changes: 1 addition & 1 deletion responsible-ai-moderationlayer/src/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def get_bearer_token():
if response.status_code == 200:
Copy link

Choose a reason for hiding this comment

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

issue (code-quality): We've found these issues:

token_info = response.json()
bearer_token = token_info['access_token']
log.info(f"Bearer Token: {bearer_token}")
log.info("Bearer token successfully obtained")
# Calculate token expiration time
expires_in = token_info['expires_in']
token_expiration_time = time.time() + expires_in - 60 # Subtract 60 seconds to account for possible delays
Expand Down
141 changes: 141 additions & 0 deletions responsible-ai-moderationlayer/src/config/constants.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
'''
Copyright 2024-2025 Infosys Ltd.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''

"""
Constants for the Responsible AI Moderation Layer

This module contains all constants used throughout the application to avoid
magic numbers and improve maintainability.
"""

class ProcessingConstants:
"""Constants for text processing operations."""

# Text chunking configuration
MAX_TOKENS_PER_CHUNK = 400
DEFAULT_CHUNK_OVERLAP = 50

# API timeout configurations
DEFAULT_TIMEOUT = 30 # seconds
EXTENDED_TIMEOUT = 60 # seconds for heavy operations

# Retry configurations
MAX_RETRIES = 3
RETRY_DELAY = 1 # seconds
EXPONENTIAL_BACKOFF_BASE = 2

# Score thresholds
DEFAULT_PII_THRESHOLD = 0.4
TOXICITY_THRESHOLD = 0.6
SIMILARITY_THRESHOLD = 0.8

# Cache configurations
DEFAULT_CACHE_TTL = 3600 # 1 hour in seconds
DEFAULT_CACHE_SIZE = 1000 # maximum number of items

# File size limits
MAX_FILE_SIZE_MB = 50
MAX_TEXT_LENGTH = 100000 # characters

# Database configurations
CONNECTION_POOL_SIZE = 10
CONNECTION_TIMEOUT = 30
QUERY_TIMEOUT = 60

class HttpConstants:
"""HTTP-related constants."""

# Status codes
SUCCESS = 200
CREATED = 201
BAD_REQUEST = 400
UNAUTHORIZED = 401
FORBIDDEN = 403
NOT_FOUND = 404
INTERNAL_SERVER_ERROR = 500

# Headers
CONTENT_TYPE_JSON = "application/json"
CONTENT_TYPE_FORM = "application/x-www-form-urlencoded"
AUTHORIZATION_HEADER = "Authorization"
BEARER_PREFIX = "Bearer "

class SecurityConstants:
"""Security-related constants."""

# Token expiration
TOKEN_EXPIRATION_BUFFER = 60 # seconds
DEFAULT_TOKEN_EXPIRY = 3600 # 1 hour

# Encryption
DEFAULT_HASH_ROUNDS = 12

# Rate limiting
DEFAULT_RATE_LIMIT = 100 # requests per hour
BURST_LIMIT = 20 # requests per minute

class LoggingConstants:
"""Logging-related constants."""

# Log levels
DEBUG = "DEBUG"
INFO = "INFO"
WARNING = "WARNING"
ERROR = "ERROR"
CRITICAL = "CRITICAL"

# Log formats
TIMESTAMP_FORMAT = "%Y-%m-%d %H:%M:%S"
REQUEST_ID_PREFIX = "REQ_"

class DatabaseConstants:
"""Database-related constants."""

# Collection/Table names
MODERATION_RESULTS_COLLECTION = "ModerationResult"
LOG_COLLECTION = "log_db"
PROFANE_WORDS_COLLECTION = "ProfaneWords"

# Database types
MONGODB = "mongo"
POSTGRESQL = "psql"
COSMOSDB = "cosmos"

class ModelConstants:
"""Model-related constants."""

# Environment targets
AZURE_ENV = "azure"
AICLOUD_ENV = "aicloud"

# Model names
GPT4 = "gpt4"
GPT3 = "gpt3"
LLAMA3 = "Llama3-70b"
GEMINI_FLASH = "Gemini-Flash"
GEMINI_PRO = "Gemini-Pro"
AWS_CLAUDE = "AWS_CLAUDE_V3_5"

class ValidationConstants:
"""Input validation constants."""

# String length limits
MAX_USERNAME_LENGTH = 50
MAX_EMAIL_LENGTH = 254
MIN_PASSWORD_LENGTH = 8
MAX_DESCRIPTION_LENGTH = 500

# List size limits
MAX_MODERATION_CHECKS = 50
MAX_ENTITY_LIST_SIZE = 100

# Regex patterns (basic examples - should be more comprehensive in production)
EMAIL_PATTERN = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
UUID_PATTERN = r'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'
13 changes: 12 additions & 1 deletion responsible-ai-moderationlayer/src/router/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,18 @@ def generate_text():
if token_env=='others':
if authorization != None:
log.info("got auth from headers")
decoded_token = jwt.decode(authorization.split(" ")[1], algorithms=["HS256"], options={"verify_signature": False})
# Enable JWT signature verification for security
jwt_secret = os.getenv("JWT_SECRET_KEY", "your-secret-key-here")
Copy link

Choose a reason for hiding this comment

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

🚨 issue (security): Default JWT secret may pose a security risk if not set in production.

Hardcoding a default secret can expose the application to attacks if the environment variable is not set. In production, ensure JWT_SECRET_KEY is required and fail fast if missing.

try:
if os.getenv("DEVELOPMENT_MODE") == "true":
log.warning("Development mode: JWT signature verification disabled")
decoded_token = jwt.decode(authorization.split(" ")[1], algorithms=["HS256"], options={"verify_signature": False})
else:
decoded_token = jwt.decode(authorization.split(" ")[1], key=jwt_secret, algorithms=["HS256"], options={"verify_signature": True})
Comment on lines +89 to +93
Copy link

Choose a reason for hiding this comment

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

🚨 suggestion (security): Development mode disables JWT signature verification, which should be tightly controlled.

Ensure that disabling JWT signature verification is impossible in production by strictly validating the environment variable. Document the associated risks clearly.

Suggested change
if os.getenv("DEVELOPMENT_MODE") == "true":
log.warning("Development mode: JWT signature verification disabled")
decoded_token = jwt.decode(authorization.split(" ")[1], algorithms=["HS256"], options={"verify_signature": False})
else:
decoded_token = jwt.decode(authorization.split(" ")[1], key=jwt_secret, algorithms=["HS256"], options={"verify_signature": True})
# WARNING: Disabling JWT signature verification is a critical security risk.
# This should ONLY be allowed in local development environments.
# Never set DEVELOPMENT_MODE="true" in production!
development_mode = os.getenv("DEVELOPMENT_MODE", "false").lower() == "true"
if development_mode:
log.warning("Development mode: JWT signature verification disabled. DO NOT USE IN PRODUCTION. This exposes the system to token forgery and impersonation risks.")
decoded_token = jwt.decode(authorization.split(" ")[1], algorithms=["HS256"], options={"verify_signature": False})
else:
decoded_token = jwt.decode(authorization.split(" ")[1], key=jwt_secret, algorithms=["HS256"], options={"verify_signature": True})

except jwt.ExpiredSignatureError:
raise InvalidTokenException("Token has expired")
except jwt.InvalidTokenError:
raise InvalidTokenException("Invalid token")
X_Correlation_ID = request.headers.get('X-Correlation-ID')
X_Span_ID = request.headers.get('X-Span-ID')
if 'unique_name' in decoded_token:
Expand Down
10 changes: 8 additions & 2 deletions responsible-ai-moderationlayer/src/service/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,14 @@ async def post_request(url, data=None, json=None, headers=None, verify=sslv[veri
headers["Authorization"]="None"

ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
# Enable proper SSL verification for security
if os.getenv("DEVELOPMENT_MODE") != "true":
ssl_context.check_hostname = True
ssl_context.verify_mode = ssl.CERT_REQUIRED
else:
log.warning("Development mode: SSL verification disabled")
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
Comment on lines 166 to +174
Copy link

Choose a reason for hiding this comment

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

🚨 suggestion (security): Enabling SSL verification in non-development mode is a good step, but fallback logic could be improved.

Explicitly check for production or staging environments to prevent misconfiguration, and validate that DEVELOPMENT_MODE only accepts expected values.

Suggested change
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
# Enable proper SSL verification for security
if os.getenv("DEVELOPMENT_MODE") != "true":
ssl_context.check_hostname = True
ssl_context.verify_mode = ssl.CERT_REQUIRED
else:
log.warning("Development mode: SSL verification disabled")
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
ssl_context = ssl.create_default_context()
# Enable proper SSL verification for security
environment = os.getenv("ENVIRONMENT", "development").lower()
development_mode = os.getenv("DEVELOPMENT_MODE", "false").lower()
valid_dev_modes = {"true", "false"}
if development_mode not in valid_dev_modes:
log.warning(f"Unexpected DEVELOPMENT_MODE value: '{development_mode}'. Defaulting to 'false' (SSL enabled).")
development_mode = "false"
if environment in {"production", "staging"} or development_mode == "false":
ssl_context.check_hostname = True
ssl_context.verify_mode = ssl.CERT_REQUIRED
else:
log.warning("Development mode: SSL verification disabled")
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE


async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=ssl_context)) as session:
async with session.post(url, data=data, json=json, headers=headers) as response:
Expand Down
4 changes: 2 additions & 2 deletions responsible-ai-moderationlayer/src/telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ def send_telemetry_request(moderation_telemetry_request,id,lotNumber,portfolioNa
headers=headers,
auth=HTTPBasicAuth( username, password),
data=json.dumps(payload),
verify = False
verify=sslv[verify_ssl]
)

if response.status_code >= 200 and response.status_code < 300:
Expand Down Expand Up @@ -394,7 +394,7 @@ def send_telemetry_error_request(moderation_telemetry_request,id,lotNumber,portf
headers=headers,
auth=HTTPBasicAuth(username, password),
data=json.dumps(payload),
verify = False
verify=sslv[verify_ssl]
)

if response.status_code >= 200 and response.status_code < 300:
Expand Down
Loading