Skip to main content

A secure environment variable manager with encryption support

Project description

๐Ÿ” 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! ๐Ÿ”

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

forenv-1.0.0.tar.gz (21.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

forenv-1.0.0-py3-none-any.whl (20.2 kB view details)

Uploaded Python 3

File details

Details for the file forenv-1.0.0.tar.gz.

File metadata

  • Download URL: forenv-1.0.0.tar.gz
  • Upload date:
  • Size: 21.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.0

File hashes

Hashes for forenv-1.0.0.tar.gz
Algorithm Hash digest
SHA256 156a3d1808d116cb73a8d681d8d174ef099129fb8e025dda5bc652fab4bfc1f7
MD5 803fd5bf90ba42f66adf5921bc04020d
BLAKE2b-256 ddd9de8ff6a94db1c338656b3d7fd46027d7f4d037321f0459a8f71cf4553eca

See more details on using hashes here.

File details

Details for the file forenv-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: forenv-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 20.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.0

File hashes

Hashes for forenv-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 206cdb1b2b487ec1f8f5f3e2ee6eec1852da5fa0ec8b8de0f881a9a5b6a6f08d
MD5 74d20ae1107b769fdd8787551a7efe5e
BLAKE2b-256 0e8bcbf0eaedcf89a1a083fec4a4091546284d717573bd0e0249a031824b7c59

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page