Metadata-Version: 2.2
Name: forenv
Version: 1.0.0
Summary: A secure environment variable manager with encryption support
Author-email: Debashish Roy <thedeba@icloud.com>
License: MIT License
        
        Copyright (c) 2026 Forenv Contributors
        
        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.
Project-URL: Homepage, https://github.com/thedeba/forenv
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: cryptography>=41.0.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: click>=8.0.0
Requires-Dist: rich>=13.0.0

# 🔐 Forenv - Fortified Environment Manager

[![Python Version](https://img.shields.io/badge/python-3.8+-blue.svg)](https://python.org)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Security](https://img.shields.io/badge/security-AES--256-red.svg)](https://cryptography.io)

**Forenv** is a powerful environment variable manager that keeps your sensitive information secure. It doesn't just read `.env` files; it provides maximum protection for your data through encryption, validation, and secure key management.

## 📋 Why Use Forenv?

### Problems with regular .env:

# ❌ Problem 1: Secret data in plain text
cat .env
DATABASE_PASSWORD=mysecretpassword  # Anyone can see this!
API_SECRET_KEY=sk-123456789        # Dangerous if pushed to Git!

# ❌ Problem 2: No validation
DB_PORT=not_a_number  # Your program will crash
TIMEOUT=invalid       # No error will be shown

# ❌ Problem 3: Unsafe team sharing
# Sending passwords via WhatsApp? 🤔

# ❌ Problem 4: Hard to remove from Git history
git log -p | grep "PASSWORD"  # Oops! It's in the history!
How Forenv Solves These Problems:
# ✅ Solution 1: Encryption
forenv encrypt .env
# Creates .env.encrypted - nobody can read it!

# ✅ Solution 2: Auto-validation
forenv validate .env --required DATABASE_URL API_KEY
# Shows error if any variable is missing

# ✅ Solution 3: Secure sharing
forenv encrypt .env --password "team_password"
# Team members use the same password

# ✅ Solution 4: Git safe
echo ".env" >> .gitignore
git add .env.encrypted  # Commit only encrypted version
🎯 Who Should Use Forenv?
✅ Use Forenv if:
Your project has API keys, passwords, tokens

You work with a team

You deploy to production environment

You need to push config to Git repository

You need GDPR, HIPAA compliance

You need to pass security audits

❌ Skip Forenv if:
Just a personal project (no secrets)

Solo development only

Only non-sensitive config like APP_NAME, DEBUG

🚀 Installation
Standard Installation:
pip install forenv

Development Installation:
git clone https://github.com/yourusername/forenv.git
cd forenv
pip install -e .[dev]

📚 Complete Usage Guide
1️⃣ Basic Usage
Create a .env file first:
# .env file
DATABASE_URL=postgresql://localhost:5432/mydb
API_KEY=sk-1234567890abcdef
SECRET_KEY=my-super-secret-key
DEBUG=true
PORT=8000

Use in Python code:
from forenv import load_env, get_env, set_env, has_env

# Load .env file
load_env('.env')

# Read variables
db_url = get_env('DATABASE_URL')
api_key = get_env('API_KEY')
debug_mode = get_env('DEBUG', 'false') == 'true'

print(f"Database: {db_url}")
print(f"API Key: {api_key[:10]}...")
print(f"Debug mode: {debug_mode}")

# Set new variable
set_env('APP_VERSION', '1.0.0')

# Check if variable exists
if has_env('SECRET_KEY'):
    print("Secret key found!")

2️⃣ Validation
Check required variables:
from forenv import load_env

# These variables must exist
load_env('.env', required_vars=[
    'DATABASE_URL',
    'API_KEY', 
    'SECRET_KEY'
])
# Raises ValidationError if any variable is missing

Type and format validation:
from forenv import validate_env
from forenv import get_env

# Define validation schema
schema = {
    'DB_PORT': {
        'type': 'int',
        'min': 1000,
        'max': 9999
    },
    'EMAIL': {
        'type': 'email',
        'pattern': r'^[\w\.-]+@[\w\.-]+\.\w+$'
    },
    'API_KEY': {
        'min_length': 20,
        'max_length': 100,
        'pattern': r'^sk-[A-Za-z0-9]+$'
    },
    'DEBUG': {
        'type': 'bool',
        'choices': ['true', 'false', 'True', 'False']
    }
}

# Validate
errors = validate_env({
    'DB_PORT': get_env('DB_PORT'),
    'EMAIL': get_env('EMAIL'),
    'API_KEY': get_env('API_KEY'),
    'DEBUG': get_env('DEBUG')
}, schema)

if errors:
    print(f"Validation failed: {errors}")
else:
    print("All validations passed!")

3️⃣ Encryption & Decryption
First-time setup (do once):
# Generate encryption key
forenv generate-key

# Output: ✅ Generated key: .env.key
# ⚠️ Keep this key secure! Store it in a safe place.
Encrypt .env file:
# Basic encryption
forenv encrypt .env

# Encryption with password
forenv encrypt .env --password "my_strong_password"

# Custom output file
forenv encrypt .env --output config.encrypted
Use encrypted file:
from forenv import load_env, get_env

# Load with key file (easy way)
load_env('.env.encrypted')

# Load with password
load_env('.env.encrypted', encryption_password="my_strong_password")

# Use normally
db_url = get_env('DATABASE_URL')
Decrypt (when needed):
# Basic decryption
forenv decrypt .env.encrypted

# Decrypt with password
forenv decrypt .env.encrypted --password "my_strong_password"

# Custom output
forenv decrypt .env.encrypted --output .env.decrypted
4️⃣ CLI Commands
# 📋 Show help
forenv --help

# 🔐 Generate key
forenv generate-key

# 📄 Show .env content (masks secrets)
forenv show .env

# ✅ Validate
forenv validate .env
forenv validate .env --required DATABASE_URL API_KEY

# 🔒 Encrypt
forenv encrypt .env
forenv encrypt .env --password "secret"

# 🔓 Decrypt
forenv decrypt .env.encrypted
forenv decrypt .env.encrypted --password "secret"

# 📋 List loaded variables
forenv list-vars
forenv list-vars --var DATABASE_URL API_KEY
5️⃣ Real-world Examples
Example 1: Django Project Configuration
# settings.py
from forenv import load_env, get_env
from pathlib import Path

# Load encrypted config file
env_file = Path(__file__).parent / '.env.encrypted'
load_env(env_file, required_vars=[
    'SECRET_KEY',
    'DATABASE_URL',
    'REDIS_URL'
])

# Use config variables safely
SECRET_KEY = get_env('SECRET_KEY')
DEBUG = get_env('DEBUG', 'False') == 'True'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'URL': get_env('DATABASE_URL')
    }
}

# API Keys
STRIPE_API_KEY = get_env('STRIPE_API_KEY')
SENDGRID_API_KEY = get_env('SENDGRID_API_KEY')
Example 2: FastAPI Application
# config.py
from forenv import load_env, get_env
from pydantic import BaseSettings

class Settings(BaseSettings):
    # Load from .env
    load_env('.env.encrypted')
    
    # Define variables
    database_url: str = get_env('DATABASE_URL')
    api_key: str = get_env('API_KEY')
    secret_key: str = get_env('SECRET_KEY')
    debug: bool = get_env('DEBUG', 'False') == 'True'
    port: int = int(get_env('PORT', '8000'))
    
    class Config:
        env_file = '.env.encrypted'
Example 3: CI/CD Pipeline (GitHub Actions)
yaml
# .github/workflows/deploy.yml
name: Deploy

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      
      - name: Decrypt environment
        run: |
          forenv decrypt .env.encrypted \
            --password ${{ secrets.ENV_PASSWORD }}
      
      - name: Validate environment
        run: |
          forenv validate .env \
            --required DATABASE_URL API_KEY SECRET_KEY
      
      - name: Run app
        run: |
          python app.py

Example 4: Docker Compose
# Dockerfile
FROM python:3.9

WORKDIR /app
COPY requirements.txt .
RUN pip install forenv

COPY .env.encrypted .
COPY entrypoint.sh .

RUN chmod +x entrypoint.sh
ENTRYPOINT ["./entrypoint.sh"]

# entrypoint.sh
#!/bin/ 

# Decrypt and load
forenv decrypt .env.encrypted --password "$ENV_PASSWORD"
forenv validate .env --required DATABASE_URL

# Start app
python app.py
6️⃣ Advanced Features
Multiple Environments:

import os
from forenv import load_env

environment = os.getenv('APP_ENV', 'development')

if environment == 'production':
    load_env('.env.prod.encrypted')
elif environment == 'staging':
    load_env('.env.staging.encrypted')
else:
    load_env('.env.dev.encrypted')
Custom Validators:
python
from forenv.validators.env_validator import validate_env

def custom_validator(value):
    """Custom validation function"""
    return value.startswith('prod_') and len(value) > 10

schema = {
    'ENVIRONMENT': custom_validator
}

validate_env({'ENVIRONMENT': 'prod_12345'}, schema)
Logging & Monitoring:

from forenv.utils.logger import setup_logger

# Custom logging setup
logger = setup_logger('myapp', level='DEBUG', log_file='app.log')

# Now all forenv logs will also save to this file
load_env('.env', required_vars=['API_KEY'])
📊 Performance Comparison
Operation	python-dotenv	forenv
Load time (100 vars)	0.001s	0.01s
Memory usage	1MB	2MB
Security	❌ None	✅ AES-256
Validation	❌ No	✅ Yes
Encryption	❌ No	✅ Yes
🛡️ Security Best Practices
✅ Do's:

# 1. Always add .env.key to .gitignore
echo ".env.key" >> .gitignore

# 2. Commit only encrypted files
git add .env.encrypted

# 3. Use strong passwords
forenv encrypt .env --password "Str0ng!Passw0rd#2024"

# 4. Rotate keys regularly (every 3 months)
forenv generate-key --rotate

# 5. Keep access logs
forenv validate .env --log-access
❌ Don'ts:

# 1. Never commit plain text .env
git add .env  # NEVER!

# 2. Don't hardcode passwords
password = "mysecret"  # DON'T!

# 3. Don't print secrets in logs
print(get_env('API_KEY'))  # DON'T!

# 4. Don't share keys through unsecured channels
# Don't send via WhatsApp, Email
🐛 Troubleshooting
Error: "Key file not found"

# Solution: Generate key file
forenv generate-key
Error: "Decryption failed"
 
# Solution: Use correct password or key
forenv decrypt .env.encrypted --password "correct_password"
Error: "Missing required variables"
 
# Solution: Add missing variables to .env file
echo "DATABASE_URL=postgresql://..." >> .env
📖 API Reference
Core Functions:
python
load_env(env_file, required_vars=None, override=True)
get_env(key, default=None)
set_env(key, value)
has_env(key)
validate_env(variables, schema=None)
Encryption Functions:
python
encrypt_file(input_file, output_file=None, key=None, password=None)
decrypt_file(input_file, output_file=None, key=None, password=None)
generate_key(key_file=None)
encrypt_string(plaintext, key)
decrypt_string(ciphertext, key)
🤝 Contribution
To contribute:

 
git clone https://github.com/yourusername/forenv.git
cd forenv
pip install -e .[dev]
pytest tests/ --cov=forenv
📄 License
MIT License - Free to use, modify, and share!

🎯 Summary
Use Forenv if:

✅ Security is important to you

✅ You work with a team

✅ You deploy production apps

✅ You have compliance requirements

Skip Forenv if:

❌ Just local development

❌ You work alone

❌ No secret data exists

Remember: Security is a process, not a product. Forenv gives you the tools to protect your data, but following best practices is your responsibility! 🔐
