Skip to content

borghei/Claude-Skills / engineering/secrets-vault-manager

secrets-vault-manager

Verified

Generates HashiCorp Vault configs, plans secret rotation from an inventory, and flags suspicious access in Vault audit logs. Use when setting up Vault, scheduling rotation, or investigating secret access.

scripts/vault_config_generator.py

View on GitHub
#!/usr/bin/env python3
"""
Vault Config Generator - Generate HashiCorp Vault configurations.

Creates HCL configuration files for Vault secrets engines, auth methods,
access policies, and audit backends based on environment requirements.

License: MIT
"""

import argparse
import json
import os
import sys
from dataclasses import dataclass, field
from pathlib import Path
from typing import List, Dict, Optional
import textwrap


SUPPORTED_ENGINES = ["kv", "database", "transit", "pki", "aws", "ssh"]
SUPPORTED_AUTH = ["approle", "kubernetes", "oidc", "token", "userpass"]
ENVIRONMENTS = ["development", "staging", "production"]


@dataclass
class VaultConfig:
    """Vault configuration parameters."""
    environment: str
    secrets_engines: List[str]
    auth_methods: List[str]
    namespace: str = ""
    audit_enabled: bool = True
    ha_enabled: bool = False
    tls_enabled: bool = True
    max_lease_ttl: str = "768h"
    default_lease_ttl: str = "768h"


def generate_main_config(config: VaultConfig) -> str:
    """Generate main Vault server configuration."""
    tls_block = ""
    if config.tls_enabled:
        tls_block = textwrap.dedent("""\
            tls_cert_file = "/etc/vault/tls/vault.crt"
            tls_key_file  = "/etc/vault/tls/vault.key"
            tls_min_version = "tls12"
        """)
    else:
        tls_block = '    tls_disable = true\n'

    ha_block = ""
    if config.ha_enabled:
        ha_block = textwrap.dedent("""\

        # HA Storage Backend (Raft)
        storage "raft" {
          path    = "/opt/vault/data"
          node_id = "vault-node-1"

          retry_join {
            leader_api_addr = "https://vault-node-2:8200"
          }
          retry_join {
            leader_api_addr = "https://vault-node-3:8200"
          }
        }

        # HA Settings
        api_addr     = "https://vault-node-1:8200"
        cluster_addr = "https://vault-node-1:8201"
        """)
    else:
        ha_block = textwrap.dedent("""\

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

    audit_block = ""
    if config.audit_enabled:
        audit_block = textwrap.dedent("""\

        # Audit Backend
        # Enable via CLI: vault audit enable file file_path=/var/log/vault/audit.log
        # vault audit enable syslog tag="vault"
        """)

    hcl = textwrap.dedent(f"""\
        # =============================================================
        # HashiCorp Vault Configuration
        # Environment: {config.environment}
        # Generated by: Vault Config Generator
        # =============================================================

        # Listener Configuration
        listener "tcp" {{
          address       = "0.0.0.0:8200"
          cluster_address = "0.0.0.0:8201"
        {tls_block}}}
        {ha_block}
        # General Settings
        max_lease_ttl     = "{config.max_lease_ttl}"
        default_lease_ttl = "{config.default_lease_ttl}"
        ui                = {str(config.environment != "production").lower()}
        log_level         = "{"info" if config.environment == "production" else "debug"}"
        {audit_block}
        # Telemetry
        telemetry {{
          prometheus_retention_time = "24h"
          disable_hostname         = true
        }}
    """)
    return hcl


def generate_secrets_engine_config(engine: str, env: str) -> str:
    """Generate secrets engine configuration script."""
    configs = {
        "kv": textwrap.dedent(f"""\
            # KV Secrets Engine (v2)
            # Enable versioned key-value store
            vault secrets enable -path=secret -version=2 kv

            # Configure max versions
            vault write secret/config max_versions=10

            # Create initial paths
            vault kv put secret/{env}/app placeholder=true
            vault kv put secret/{env}/database placeholder=true
            vault kv put secret/{env}/api-keys placeholder=true

            echo "KV v2 secrets engine enabled at secret/"
        """),
        "database": textwrap.dedent(f"""\
            # Database Secrets Engine
            vault secrets enable database

            # PostgreSQL Configuration (update connection details)
            vault write database/config/postgresql-{env} \\
                plugin_name=postgresql-database-plugin \\
                allowed_roles="readonly-{env},readwrite-{env}" \\
                connection_url="postgresql://{{{{username}}}}:{{{{password}}}}@db-{env}:5432/app?sslmode=require" \\
                username="vault_admin" \\
                password="CHANGE_ME"

            # Read-only role (TTL: 1 hour)
            vault write database/roles/readonly-{env} \\
                db_name=postgresql-{env} \\
                creation_statements="CREATE ROLE \\"{{{{name}}}}\\" WITH LOGIN PASSWORD '{{{{password}}}}' VALID UNTIL '{{{{expiration}}}}'; GRANT SELECT ON ALL TABLES IN SCHEMA public TO \\"{{{{name}}}}\\";" \\
                default_ttl="1h" \\
                max_ttl="24h"

            # Read-write role (TTL: 1 hour)
            vault write database/roles/readwrite-{env} \\
                db_name=postgresql-{env} \\
                creation_statements="CREATE ROLE \\"{{{{name}}}}\\" WITH LOGIN PASSWORD '{{{{password}}}}' VALID UNTIL '{{{{expiration}}}}'; GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO \\"{{{{name}}}}\\";" \\
                default_ttl="1h" \\
                max_ttl="24h"

            echo "Database secrets engine configured for {env}"
        """),
        "transit": textwrap.dedent(f"""\
            # Transit Secrets Engine (Encryption as a Service)
            vault secrets enable transit

            # Create encryption key for application data
            vault write -f transit/keys/app-{env} \\
                type=aes256-gcm96 \\
                min_decryption_version=1 \\
                min_encryption_version=1 \\
                deletion_allowed=false

            # Create key for PII encryption
            vault write -f transit/keys/pii-{env} \\
                type=aes256-gcm96 \\
                exportable=false \\
                deletion_allowed=false

            echo "Transit secrets engine configured with encryption keys for {env}"
        """),
        "pki": textwrap.dedent(f"""\
            # PKI Secrets Engine
            vault secrets enable pki

            # Set max TTL to 1 year
            vault secrets tune -max-lease-ttl=8760h pki

            # Generate root CA (for non-production) or set CA cert
            vault write pki/root/generate/internal \\
                common_name="{env}.internal" \\
                ttl=8760h

            # Configure URLs
            vault write pki/config/urls \\
                issuing_certificates="https://vault.{env}.internal:8200/v1/pki/ca" \\
                crl_distribution_points="https://vault.{env}.internal:8200/v1/pki/crl"

            # Create role for issuing certificates
            vault write pki/roles/{env}-services \\
                allowed_domains="{env}.internal" \\
                allow_subdomains=true \\
                max_ttl=72h

            echo "PKI engine configured for {env}"
        """),
        "aws": textwrap.dedent(f"""\
            # AWS Secrets Engine
            vault secrets enable aws

            # Configure AWS credentials (use IAM role if on EC2)
            vault write aws/config/root \\
                access_key="CHANGE_ME" \\
                secret_key="CHANGE_ME" \\
                region="us-east-1"

            # Create role for S3 access
            vault write aws/roles/s3-{env} \\
                credential_type=iam_user \\
                policy_document=@- <<EOF
            {{
                "Version": "2012-10-17",
                "Statement": [
                    {{
                        "Effect": "Allow",
                        "Action": ["s3:GetObject", "s3:PutObject", "s3:ListBucket"],
                        "Resource": ["arn:aws:s3:::{env}-*"]
                    }}
                ]
            }}
            EOF

            echo "AWS secrets engine configured for {env}"
        """),
        "ssh": textwrap.dedent(f"""\
            # SSH Secrets Engine (Certificate Signing)
            vault secrets enable -path=ssh-client-signer ssh

            # Generate signing key
            vault write ssh-client-signer/config/ca generate_signing_key=true

            # Create role for SSH certificate signing
            vault write ssh-client-signer/roles/{env}-ssh-role \\
                key_type=ca \\
                default_user=ubuntu \\
                allowed_users="ubuntu,deploy,app" \\
                ttl=30m \\
                max_ttl=4h \\
                allow_user_certificates=true

            echo "SSH secrets engine configured for {env}"
        """),
    }
    return configs.get(engine, f"# Unknown engine: {engine}\n")


def generate_auth_config(method: str, env: str) -> str:
    """Generate auth method configuration."""
    configs = {
        "approle": textwrap.dedent(f"""\
            # AppRole Auth Method
            vault auth enable approle

            # Create role for application
            vault write auth/approle/role/app-{env} \\
                token_ttl=1h \\
                token_max_ttl=4h \\
                secret_id_ttl=720h \\
                token_policies="app-{env}-policy" \\
                bind_secret_id=true

            echo "AppRole auth configured for {env}"
        """),
        "kubernetes": textwrap.dedent(f"""\
            # Kubernetes Auth Method
            vault auth enable kubernetes

            vault write auth/kubernetes/config \\
                kubernetes_host="https://kubernetes.default.svc:443"

            # Create role for app pods
            vault write auth/kubernetes/role/app-{env} \\
                bound_service_account_names="app-sa" \\
                bound_service_account_namespaces="{env}" \\
                policies="app-{env}-policy" \\
                ttl=1h

            echo "Kubernetes auth configured for {env}"
        """),
        "oidc": textwrap.dedent(f"""\
            # OIDC Auth Method
            vault auth enable oidc

            vault write auth/oidc/config \\
                oidc_discovery_url="https://accounts.google.com" \\
                oidc_client_id="CHANGE_ME" \\
                oidc_client_secret="CHANGE_ME" \\
                default_role="default"

            vault write auth/oidc/role/default \\
                bound_audiences="CHANGE_ME" \\
                allowed_redirect_uris="https://vault.{env}.internal:8200/ui/vault/auth/oidc/oidc/callback" \\
                user_claim="sub" \\
                policies="default"

            echo "OIDC auth configured for {env}"
        """),
        "token": textwrap.dedent("""\
            # Token Auth (built-in, no configuration needed)
            # Tokens are managed via vault token create
            echo "Token auth is enabled by default"
        """),
        "userpass": textwrap.dedent(f"""\
            # Userpass Auth (dev/testing only)
            vault auth enable userpass

            # WARNING: Not recommended for production
            vault write auth/userpass/users/admin \\
                password="CHANGE_ME" \\
                policies="admin-policy"

            echo "Userpass auth configured (NOT for production use)"
        """),
    }
    return configs.get(method, f"# Unknown auth method: {method}\n")


def generate_policy(env: str) -> str:
    """Generate default access policy."""
    return textwrap.dedent(f"""\
        # =============================================================
        # Vault Policy: app-{env}-policy
        # Environment: {env}
        # =============================================================

        # KV secrets - read only
        path "secret/data/{env}/*" {{
          capabilities = ["read", "list"]
        }}

        # Database credentials - generate
        path "database/creds/readonly-{env}" {{
          capabilities = ["read"]
        }}

        # Transit encryption/decryption
        path "transit/encrypt/app-{env}" {{
          capabilities = ["update"]
        }}
        path "transit/decrypt/app-{env}" {{
          capabilities = ["update"]
        }}

        # PKI - issue certificates
        path "pki/issue/{env}-services" {{
          capabilities = ["create", "update"]
        }}

        # Deny access to other environments
        path "secret/data/{"production" if env != "production" else "development"}/*" {{
          capabilities = ["deny"]
        }}

        # Self-management
        path "auth/token/lookup-self" {{
          capabilities = ["read"]
        }}
        path "auth/token/renew-self" {{
          capabilities = ["update"]
        }}
    """)


def format_output(config: VaultConfig) -> str:
    """Generate all configurations and format output."""
    lines = []
    lines.append("=" * 70)
    lines.append(f"VAULT CONFIGURATION - {config.environment.upper()}")
    lines.append("=" * 70)
    lines.append(f"Environment: {config.environment}")
    lines.append(f"Secrets Engines: {', '.join(config.secrets_engines)}")
    lines.append(f"Auth Methods: {', '.join(config.auth_methods)}")
    lines.append(f"TLS: {'enabled' if config.tls_enabled else 'disabled'}")
    lines.append(f"HA: {'enabled' if config.ha_enabled else 'disabled'}")
    lines.append(f"Audit: {'enabled' if config.audit_enabled else 'disabled'}")
    lines.append("")

    lines.append("--- vault.hcl ---")
    lines.append(generate_main_config(config))

    for engine in config.secrets_engines:
        lines.append(f"--- setup_{engine}.sh ---")
        lines.append(generate_secrets_engine_config(engine, config.environment))

    for method in config.auth_methods:
        lines.append(f"--- auth_{method}.sh ---")
        lines.append(generate_auth_config(method, config.environment))

    lines.append(f"--- policy_app_{config.environment}.hcl ---")
    lines.append(generate_policy(config.environment))

    return "\n".join(lines)


def save_configs(config: VaultConfig, output_dir: Path):
    """Save configuration files to directory."""
    output_dir.mkdir(parents=True, exist_ok=True)

    (output_dir / "vault.hcl").write_text(generate_main_config(config))

    for engine in config.secrets_engines:
        (output_dir / f"setup_{engine}.sh").write_text(
            generate_secrets_engine_config(engine, config.environment))

    for method in config.auth_methods:
        (output_dir / f"auth_{method}.sh").write_text(
            generate_auth_config(method, config.environment))

    (output_dir / f"policy_app_{config.environment}.hcl").write_text(
        generate_policy(config.environment))


def main():
    parser = argparse.ArgumentParser(
        description="Vault Config Generator - Generate HashiCorp Vault configurations"
    )
    parser.add_argument("--env", required=True, choices=ENVIRONMENTS,
                        help="Target environment")
    parser.add_argument("--secrets-engines", required=True,
                        help=f"Comma-separated engines: {','.join(SUPPORTED_ENGINES)}")
    parser.add_argument("--auth-methods", default="approle,token",
                        help=f"Comma-separated auth methods: {','.join(SUPPORTED_AUTH)}")
    parser.add_argument("--output-dir", help="Directory to save config files")
    parser.add_argument("--ha", action="store_true", help="Enable HA configuration")
    parser.add_argument("--no-tls", action="store_true", help="Disable TLS (dev only)")
    parser.add_argument("--no-audit", action="store_true", help="Disable audit logging")
    parser.add_argument("--format", choices=["human", "json"], default="human",
                        help="Output format")

    args = parser.parse_args()

    engines = [e.strip() for e in args.secrets_engines.split(",")]
    auth_methods = [m.strip() for m in args.auth_methods.split(",")]

    for e in engines:
        if e not in SUPPORTED_ENGINES:
            print(f"Error: Unknown secrets engine '{e}'. Supported: {SUPPORTED_ENGINES}", file=sys.stderr)
            sys.exit(2)

    config = VaultConfig(
        environment=args.env,
        secrets_engines=engines,
        auth_methods=auth_methods,
        ha_enabled=args.ha,
        tls_enabled=not args.no_tls,
        audit_enabled=not args.no_audit,
    )

    if args.output_dir:
        save_configs(config, Path(args.output_dir))
        print(f"Configurations saved to {args.output_dir}/")
    elif args.format == "json":
        data = {
            "environment": config.environment,
            "secrets_engines": config.secrets_engines,
            "auth_methods": config.auth_methods,
            "files_generated": [
                "vault.hcl",
                *[f"setup_{e}.sh" for e in engines],
                *[f"auth_{m}.sh" for m in auth_methods],
                f"policy_app_{config.environment}.hcl",
            ],
        }
        print(json.dumps(data, indent=2))
    else:
        print(format_output(config))


if __name__ == "__main__":
    main()
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall