# Environment Variable Encryption

Yemaya provides built-in encryption for sensitive environment variables using
AES-256-GCM authenticated encryption.

## Overview

Sensitive values like API keys, database passwords, and secrets can be encrypted
at rest in your `.env` files. The configuration loader automatically decrypts
these values at runtime using a master key.

## Quick Start

### 1. Generate a Master Key

```bash
pnpm env:generate-key
```

This outputs a secure 256-bit key encoded in base64. Store this key securely.

### 2. Set the Master Key

Choose one of these methods:

**Environment Variable (recommended for development):**

```bash
export YEMAYA_MASTER_KEY="your-generated-key"
```

**File (recommended for production):**

```bash
echo "your-generated-key" > /path/to/master.key
chmod 600 /path/to/master.key
export YEMAYA_MASTER_KEY_FILE="/path/to/master.key"
```

**Docker Secrets (recommended for Swarm/Kubernetes):**

```bash
echo "your-generated-key" | docker secret create yemaya_master_key -
```

### 3. Encrypt Your Environment File

```bash
YEMAYA_MASTER_KEY="your-key" pnpm env:encrypt .env.production
```

This encrypts all sensitive values in place. Sensitive keys are detected
automatically based on common patterns (PASSWORD, SECRET, KEY, TOKEN, etc.).

### 4. Use Encrypted Values

The configuration loader automatically decrypts values at runtime:

```typescript
import { loadConfig } from '@yemaya/core';

const config = loadConfig();
// config.database.url is automatically decrypted
```

## CLI Commands

### Encrypt a File

```bash
# Encrypt .env (default)
pnpm env:encrypt

# Encrypt specific file
pnpm env:encrypt .env.production

# Output to different file
pnpm env:encrypt .env.production -o .env.production.encrypted
```

### Decrypt a File

```bash
# Decrypt .env.encrypted (default)
pnpm env:decrypt

# Decrypt specific file
pnpm env:decrypt .env.production

# Output to different file
pnpm env:decrypt .env.encrypted -o .env.local
```

### Encrypt Single Value

```bash
pnpm env:encrypt-value "my-secret-password"
# Output: ENC:v1:salt:iv:authTag:ciphertext
```

### Decrypt Single Value

```bash
pnpm env:decrypt-value "ENC:v1:..."
# Output: my-secret-password
```

### Generate New Key

```bash
pnpm env:generate-key
```

## Encrypted Value Format

Encrypted values use the format:

```
ENC:v1:<salt>:<iv>:<authTag>:<ciphertext>
```

- `ENC` - Prefix identifying encrypted values
- `v1` - Format version
- `salt` - 32-byte salt for key derivation (hex)
- `iv` - 16-byte initialization vector (hex)
- `authTag` - 16-byte authentication tag (hex)
- `ciphertext` - Encrypted data (hex)

## Sensitive Key Detection

The following patterns are automatically detected as sensitive:

- `PASSWORD`
- `SECRET`
- `KEY`
- `TOKEN`
- `CREDENTIAL`
- `PRIVATE`
- `API_KEY`
- `ACCESS_KEY`
- `SECRET_KEY`
- `AUTH`
- `DSN`
- `CONNECTION_STRING`

Examples of matched keys:

- `DATABASE_URL` (contains sensitive connection string)
- `JWT_SECRET`
- `ANTHROPIC_API_KEY`
- `REDIS_PASSWORD`
- `MINIO_SECRET_KEY`

## Programmatic Usage

### Encrypt Values

```typescript
import { encrypt, encryptEnvVars } from '@yemaya/core';

// Encrypt single value
const encrypted = encrypt('my-secret', { masterKey: 'your-master-key' });

// Encrypt multiple values
const encrypted = encryptEnvVars(
  { DATABASE_URL: 'postgres://...', APP_NAME: 'myapp' },
  { masterKey: 'your-master-key' }
);
// Only DATABASE_URL is encrypted (contains sensitive pattern)
```

### Decrypt Values

```typescript
import { decrypt, decryptEnvVars, isEncrypted } from '@yemaya/core';

// Check if encrypted
if (isEncrypted(value)) {
  const decrypted = decrypt(value, { masterKey: 'your-master-key' });
}

// Decrypt multiple values
const decrypted = decryptEnvVars(encryptedEnv, {
  masterKey: 'your-master-key',
});
```

### Get Master Key

```typescript
import { getMasterKey } from '@yemaya/core';

const key = getMasterKey(); // From env var or file
```

## Security Considerations

### Key Storage

1. **Never commit master keys to git**
2. **Use different keys per environment** (dev, staging, production)
3. **Rotate keys periodically** using the secrets manager
4. **Use secret management services** in production:
   - Docker Swarm secrets
   - Kubernetes secrets
   - HashiCorp Vault
   - AWS Secrets Manager
   - GCP Secret Manager

### Encryption Details

- **Algorithm**: AES-256-GCM (authenticated encryption)
- **Key Derivation**: scrypt with N=16384, r=8, p=1
- **Salt**: 32 bytes, unique per encryption
- **IV**: 16 bytes, randomly generated
- **Auth Tag**: 16 bytes for integrity verification

### Best Practices

1. **Encrypt production secrets only** - Development can use plaintext
2. **Audit encrypted files** - Review what's encrypted with `git diff`
3. **Test decryption** - Verify config loads correctly before deployment
4. **Backup keys securely** - Use separate backup for master keys
5. **Log carefully** - Ensure logs don't expose decrypted values

## Troubleshooting

### "No master key provided"

Set `YEMAYA_MASTER_KEY` environment variable or `YEMAYA_MASTER_KEY_FILE`.

### "Decryption failed"

- Verify you're using the correct master key
- Check the encrypted value format (should start with `ENC:v1:`)
- Ensure the value wasn't corrupted

### "Invalid encrypted value format"

The value doesn't match the expected `ENC:v1:...` format. It may be:

- Already decrypted
- Encrypted with an older/incompatible version
- Corrupted

### Config validation fails after encryption

Ensure the master key is available before loading config:

```bash
export YEMAYA_MASTER_KEY="your-key"
pnpm validate:env
```

## Integration with Docker

### Development (docker-compose.yml)

```yaml
services:
  api:
    environment:
      - YEMAYA_MASTER_KEY=${YEMAYA_MASTER_KEY}
```

### Production with Secrets

```yaml
services:
  api:
    secrets:
      - yemaya_master_key
    environment:
      - YEMAYA_MASTER_KEY_FILE=/run/secrets/yemaya_master_key

secrets:
  yemaya_master_key:
    external: true
```

## Key Rotation

To rotate the master key:

1. Decrypt all files with the old key
2. Generate a new key
3. Re-encrypt all files with the new key
4. Update secret storage with the new key
5. Deploy the new key to all environments

```bash
# Using secrets manager
./scripts/secrets-manager.sh rotate yemaya_master_key
```

## Related Documentation

- [Environment Variables](./ENVIRONMENT_VARIABLES.md)
- [Docker Secrets](../docker/secrets/README.md)
- [Security Best Practices](./SECURITY.md)
