Skip to main content

🔐 Forenv - Fortified Environment Manager

Python Version License Security

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! 🔐

Metadata

Release files for forenv 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for forenv 1.0.0
File Size Uploaded Provenance Actions
forenv-1.0.0.tar.gz 21.6 kB Without provenance Details for forenv-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for forenv 1.0.0
File Interpreter ABI Platform Actions
forenv-1.0.0-py3-none-any.whl Python 3 none any Details for forenv-1.0.0-py3-none-any.whl

Total release size: 41.8 kB

Release files / forenv-1.0.0.tar.gz

Download URL forenv-1.0.0.tar.gz
Size 21.6 kB
Tags Source
SHA-256 checksum
How to use checksums
156a3d1808d116cb73a8d681d8d174ef099129fb8e025dda5bc652fab4bfc1f7
BLAKE2b-256 checksum
How to use checksums
ddd9de8ff6a94db1c338656b3d7fd46027d7f4d037321f0459a8f71cf4553eca
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.0

Release files / forenv-1.0.0-py3-none-any.whl

Download URL forenv-1.0.0-py3-none-any.whl
Size 20.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
206cdb1b2b487ec1f8f5f3e2ee6eec1852da5fa0ec8b8de0f881a9a5b6a6f08d
BLAKE2b-256 checksum
How to use checksums
0e8bcbf0eaedcf89a1a083fec4a4091546284d717573bd0e0249a031824b7c59
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.0

Security for forenv 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page