# RustyVault KMS Backend Guide

**Version**: 1.0.0
**Date**: 2025-10-08
**Status**: Production-ready

---

## Overview

RustyVault is a self-hosted, Rust-based secrets management system that provides a **Vault-compatible API**. The provisioning platform now supports RustyVault as a KMS backend alongside Age, Cosmian, AWS KMS, and HashiCorp Vault.

### Why RustyVault

- **Self-hosted**: Full control over your key management infrastructure
- **Pure Rust**: Better performance and memory safety
- **Vault-compatible**: Drop-in replacement for HashiCorp Vault Transit engine
- **OSI-approved License**: Apache 2.0 (vs HashiCorp's BSL)
- **Embeddable**: Can run as standalone service or embedded library
- **No Vendor Lock-in**: Open-source alternative to proprietary KMS solutions

---

## Architecture Position

```plaintext
KMS Service Backends:
├── Age (local development, file-based)
├── Cosmian (privacy-preserving, production)
├── AWS KMS (cloud-native AWS)
├── HashiCorp Vault (enterprise, external)
└── RustyVault (self-hosted, embedded) ✨ NEW
```plaintext

---

## Installation

### Option 1: Standalone RustyVault Server

```bash
# Install RustyVault binary
cargo install rusty_vault

# Start RustyVault server
rustyvault server -config=/path/to/config.hcl
```plaintext

### Option 2: Docker Deployment

```bash
# Pull RustyVault image (if available)
docker pull tongsuo/rustyvault:latest

# Run RustyVault container
docker run -d \
  --name rustyvault \
  -p 8200:8200 \
  -v $(pwd)/config:/vault/config \
  -v $(pwd)/data:/vault/data \
  tongsuo/rustyvault:latest
```plaintext

### Option 3: From Source

```bash
# Clone repository
git clone https://github.com/Tongsuo-Project/RustyVault.git
cd RustyVault

# Build and run
cargo build --release
./target/release/rustyvault server -config=config.hcl
```plaintext

---

## Configuration

### RustyVault Server Configuration

Create `rustyvault-config.hcl`:

```hcl
# RustyVault Server Configuration

storage "file" {
  path = "/vault/data"
}

listener "tcp" {
  address     = "0.0.0.0:8200"
  tls_disable = true  # Enable TLS in production
}

api_addr = "http://127.0.0.1:8200"
cluster_addr = "https://127.0.0.1:8201"

# Enable Transit secrets engine
default_lease_ttl = "168h"
max_lease_ttl = "720h"
```plaintext

### Initialize RustyVault

```bash
# Initialize (first time only)
export VAULT_ADDR='http://127.0.0.1:8200'
rustyvault operator init

# Unseal (after every restart)
rustyvault operator unseal <unseal_key_1>
rustyvault operator unseal <unseal_key_2>
rustyvault operator unseal <unseal_key_3>

# Save root token
export RUSTYVAULT_TOKEN='<root_token>'
```plaintext

### Enable Transit Engine

```bash
# Enable transit secrets engine
rustyvault secrets enable transit

# Create encryption key
rustyvault write -f transit/keys/provisioning-main

# Verify key creation
rustyvault read transit/keys/provisioning-main
```plaintext

---

## KMS Service Configuration

### Update `provisioning/config/kms.toml`

```toml
[kms]
type = "rustyvault"
server_url = "http://localhost:8200"
token = "${RUSTYVAULT_TOKEN}"
mount_point = "transit"
key_name = "provisioning-main"
tls_verify = true

[service]
bind_addr = "0.0.0.0:8081"
log_level = "info"
audit_logging = true

[tls]
enabled = false  # Set true with HTTPS
```plaintext

### Environment Variables

```bash
# RustyVault connection
export RUSTYVAULT_ADDR="http://localhost:8200"
export RUSTYVAULT_TOKEN="s.xxxxxxxxxxxxxxxxxxxxxx"
export RUSTYVAULT_MOUNT_POINT="transit"
export RUSTYVAULT_KEY_NAME="provisioning-main"
export RUSTYVAULT_TLS_VERIFY="true"

# KMS service
export KMS_BACKEND="rustyvault"
export KMS_BIND_ADDR="0.0.0.0:8081"
```plaintext

---

## Usage

### Start KMS Service

```bash
# With RustyVault backend
cd provisioning/platform/kms-service
cargo run

# With custom config
cargo run -- --config=/path/to/kms.toml
```plaintext

### CLI Operations

```bash
# Encrypt configuration file
provisioning kms encrypt provisioning/config/secrets.yaml

# Decrypt configuration
provisioning kms decrypt provisioning/config/secrets.yaml.enc

# Generate data key (envelope encryption)
provisioning kms generate-key --spec AES256

# Health check
provisioning kms health
```plaintext

### REST API Usage

```bash
# Health check
curl http://localhost:8081/health

# Encrypt data
curl -X POST http://localhost:8081/encrypt \
  -H "Content-Type: application/json" \
  -d '{
    "plaintext": "SGVsbG8sIFdvcmxkIQ==",
    "context": "environment=production"
  }'

# Decrypt data
curl -X POST http://localhost:8081/decrypt \
  -H "Content-Type: application/json" \
  -d '{
    "ciphertext": "vault:v1:...",
    "context": "environment=production"
  }'

# Generate data key
curl -X POST http://localhost:8081/datakey/generate \
  -H "Content-Type: application/json" \
  -d '{"key_spec": "AES_256"}'
```plaintext

---

## Advanced Features

### Context-based Encryption (AAD)

Additional authenticated data binds encrypted data to specific contexts:

```bash
# Encrypt with context
curl -X POST http://localhost:8081/encrypt \
  -d '{
    "plaintext": "c2VjcmV0",
    "context": "environment=prod,service=api"
  }'

# Decrypt requires same context
curl -X POST http://localhost:8081/decrypt \
  -d '{
    "ciphertext": "vault:v1:...",
    "context": "environment=prod,service=api"
  }'
```plaintext

### Envelope Encryption

For large files, use envelope encryption:

```bash
# 1. Generate data key
DATA_KEY=$(curl -X POST http://localhost:8081/datakey/generate \
  -d '{"key_spec": "AES_256"}' | jq -r '.plaintext')

# 2. Encrypt large file with data key (locally)
openssl enc -aes-256-cbc -in large-file.bin -out encrypted.bin -K $DATA_KEY

# 3. Store encrypted data key (from response)
echo "vault:v1:..." > encrypted-data-key.txt
```plaintext

### Key Rotation

```bash
# Rotate encryption key in RustyVault
rustyvault write -f transit/keys/provisioning-main/rotate

# Verify new version
rustyvault read transit/keys/provisioning-main

# Rewrap existing ciphertext with new key version
curl -X POST http://localhost:8081/rewrap \
  -d '{"ciphertext": "vault:v1:..."}'
```plaintext

---

## Production Deployment

### High Availability Setup

Deploy multiple RustyVault instances behind a load balancer:

```yaml
# docker-compose.yml
version: '3.8'

services:
  rustyvault-1:
    image: tongsuo/rustyvault:latest
    ports:
      - "8200:8200"
    volumes:
      - ./config:/vault/config
      - vault-data-1:/vault/data

  rustyvault-2:
    image: tongsuo/rustyvault:latest
    ports:
      - "8201:8200"
    volumes:
      - ./config:/vault/config
      - vault-data-2:/vault/data

  lb:
    image: nginx:alpine
    ports:
      - "80:80"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
    depends_on:
      - rustyvault-1
      - rustyvault-2

volumes:
  vault-data-1:
  vault-data-2:
```plaintext

### TLS Configuration

```toml
# kms.toml
[kms]
type = "rustyvault"
server_url = "https://vault.example.com:8200"
token = "${RUSTYVAULT_TOKEN}"
tls_verify = true

[tls]
enabled = true
cert_path = "/etc/kms/certs/server.crt"
key_path = "/etc/kms/certs/server.key"
ca_path = "/etc/kms/certs/ca.crt"
```plaintext

### Auto-Unseal (AWS KMS)

```hcl
# rustyvault-config.hcl
seal "awskms" {
  region     = "us-east-1"
  kms_key_id = "arn:aws:kms:us-east-1:123456789012:key/..."
}
```plaintext

---

## Monitoring

### Health Checks

```bash
# RustyVault health
curl http://localhost:8200/v1/sys/health

# KMS service health
curl http://localhost:8081/health

# Metrics (if enabled)
curl http://localhost:8081/metrics
```plaintext

### Audit Logging

Enable audit logging in RustyVault:

```hcl
# rustyvault-config.hcl
audit {
  path = "/vault/logs/audit.log"
  format = "json"
}
```plaintext

---

## Troubleshooting

### Common Issues

**1. Connection Refused**

```bash
# Check RustyVault is running
curl http://localhost:8200/v1/sys/health

# Check token is valid
export VAULT_ADDR='http://localhost:8200'
rustyvault token lookup
```plaintext

**2. Authentication Failed**

```bash
# Verify token in environment
echo $RUSTYVAULT_TOKEN

# Renew token if needed
rustyvault token renew
```plaintext

**3. Key Not Found**

```bash
# List available keys
rustyvault list transit/keys

# Create missing key
rustyvault write -f transit/keys/provisioning-main
```plaintext

**4. TLS Verification Failed**

```bash
# Disable TLS verification (dev only)
export RUSTYVAULT_TLS_VERIFY=false

# Or add CA certificate
export RUSTYVAULT_CACERT=/path/to/ca.crt
```plaintext

---

## Migration from Other Backends

### From HashiCorp Vault

RustyVault is API-compatible, minimal changes required:

```bash
# Old config (Vault)
[kms]
type = "vault"
address = "https://vault.example.com:8200"
token = "${VAULT_TOKEN}"

# New config (RustyVault)
[kms]
type = "rustyvault"
server_url = "http://rustyvault.example.com:8200"
token = "${RUSTYVAULT_TOKEN}"
```plaintext

### From Age

Re-encrypt existing encrypted files:

```bash
# 1. Decrypt with Age
provisioning kms decrypt --backend age secrets.enc > secrets.plain

# 2. Encrypt with RustyVault
provisioning kms encrypt --backend rustyvault secrets.plain > secrets.rustyvault.enc
```plaintext

---

## Security Considerations

### Best Practices

1. **Enable TLS**: Always use HTTPS in production
2. **Rotate Tokens**: Regularly rotate RustyVault tokens
3. **Least Privilege**: Use policies to restrict token permissions
4. **Audit Logging**: Enable and monitor audit logs
5. **Backup Keys**: Secure backup of unseal keys and root token
6. **Network Isolation**: Run RustyVault in isolated network segment

### Token Policies

Create restricted policy for KMS service:

```hcl
# kms-policy.hcl
path "transit/encrypt/provisioning-main" {
  capabilities = ["update"]
}

path "transit/decrypt/provisioning-main" {
  capabilities = ["update"]
}

path "transit/datakey/plaintext/provisioning-main" {
  capabilities = ["update"]
}
```plaintext

Apply policy:

```bash
rustyvault policy write kms-service kms-policy.hcl
rustyvault token create -policy=kms-service
```plaintext

---

## Performance

### Benchmarks (Estimated)

| Operation | Latency | Throughput |
|-----------|---------|------------|
| Encrypt | 5-15 ms | 2,000-5,000 ops/sec |
| Decrypt | 5-15 ms | 2,000-5,000 ops/sec |
| Generate Key | 10-20 ms | 1,000-2,000 ops/sec |

*Actual performance depends on hardware, network, and RustyVault configuration*

### Optimization Tips

1. **Connection Pooling**: Reuse HTTP connections
2. **Batching**: Batch multiple operations when possible
3. **Caching**: Cache data keys for envelope encryption
4. **Local Unseal**: Use auto-unseal for faster restarts

---

## Related Documentation

- **KMS Service**: `docs/user/CONFIG_ENCRYPTION_GUIDE.md`
- **Dynamic Secrets**: `docs/user/DYNAMIC_SECRETS_QUICK_REFERENCE.md`
- **Security System**: `docs/architecture/ADR-009-security-system-complete.md`
- **RustyVault GitHub**: <https://github.com/Tongsuo-Project/RustyVault>

---

## Support

- **GitHub Issues**: <https://github.com/Tongsuo-Project/RustyVault/issues>
- **Documentation**: <https://github.com/Tongsuo-Project/RustyVault/tree/main/docs>
- **Community**: <https://users.rust-lang.org/t/rustyvault-a-hashicorp-vault-replacement-in-rust/103943>

---

**Last Updated**: 2025-10-08
**Maintained By**: Architecture Team
