# Compliance and Audit Example

Complete example of setting up infrastructure with compliance controls and audit logging.

## Compliance Requirements

Deploy infrastructure meeting:
- SOC2 Type II
- GDPR data residency
- HIPAA encryption
- PCI-DSS for payment processing
- NIST 800-53 security controls

## Configuration with Compliance Controls

```nickel
{
  infrastructure = {
    compliance = {
      frameworks = ["soc2", "gdpr", "hipaa", "pci-dss"],
      region = "eu-west-1",  # GDPR requirement: EU data center
      availability_zones = ["eu-west-1a", "eu-west-1b"],
    },

    compute = {
      instance_type = "t3.large",
      count = 3,
      encryption = {
        enabled = true,
        algorithm = "aes-256-gcm"
      }
    },

    storage = {
      databases = [
        {
          engine = "postgres",
          version = "15.0",
          instance_class = "db.r6i.xlarge",
          encryption = {
            enabled = true,
            kms_key_id = "arn:aws:kms:eu-west-1:xxx:key/xxx"
          },
          backup = {
            enabled = true,
            retention_days = 90,  # HIPAA: 90-day minimum
            encryption = "aes-256"
          },
          audit_logging = {
            enabled = true,
            log_retention_days = 365  # 1-year audit trail
          }
        }
      ]
    },

    security = {
      # GDPR: Encryption at rest and in transit mandatory
      encryption = {
        at_rest = true,
        in_transit = true,
        tls_version = "1.3",
        cipher_suites = [
          "TLS_AES_256_GCM_SHA384",
          "TLS_CHACHA20_POLY1305_SHA256"
        ]
      },

      # SOC2: Comprehensive audit logging
      audit_logging = {
        enabled = true,
        retention_days = 365,
        events = [
          "api_call",
          "data_access",
          "configuration_change",
          "authentication_attempt",
          "authorization_decision",
          "encryption_key_operation"
        ]
      },

      # HIPAA: Access controls
      access_control = {
        mfa_required = true,
        session_timeout_minutes = 60,
        password_policy = {
          minimum_length = 14,
          requires_uppercase = true,
          requires_lowercase = true,
          requires_numbers = true,
          requires_special_chars = true,
          expires_days = 90
        }
      },

      # NIST 800-53: Configuration management
      configuration_management = {
        baseline_hardening = true,
        cis_benchmark = "v1.4.0",
        vulnerability_scanning = {
          enabled = true,
          frequency = "daily"
        }
      }
    },

    networking = {
      vpc_cidr = "10.0.0.0/16",
      nat_gateway_count = 2,

      # PCI-DSS: Network segmentation
      subnets = [
        {
          name = "public",
          cidr = "10.0.1.0/24",
          type = "public"
        },
        {
          name = "private",
          cidr = "10.0.2.0/24",
          type = "private",
          route_to_nat = true
        },
        {
          name = "database",
          cidr = "10.0.3.0/24",
          type = "private",
          network_acl = {
            allow_postgres = true,
            deny_all_other = true
          }
        }
      ],

      security_groups = [
        {
          name = "alb",
          rules = [
            {
              protocol = "tcp",
              port = 443,
              source = "0.0.0.0/0",
              description = "HTTPS from internet"
            }
          ]
        },
        {
          name = "app",
          rules = [
            {
              protocol = "tcp",
              port = 8080,
              source = "security_group:alb",
              description = "App from ALB"
            }
          ]
        },
        {
          name = "database",
          rules = [
            {
              protocol = "tcp",
              port = 5432,
              source = "security_group:app",
              description = "PostgreSQL from app"
            }
          ]
        }
      ]
    }
  }
}
```

## Audit Logging Setup

### Event Types Captured

```nushell
# Enable comprehensive audit logging
provisioning audit enable --levels all

# Captured events:
# 1. Authentication Events
#    - Login attempts (success/failure)
#    - MFA verification
#    - Session creation/termination
#    - Token generation/revocation

# 2. Authorization Events
#    - Permission checks
#    - Policy decisions
#    - Access approvals/denials
#    - Role changes

# 3. Data Access Events
#    - Database queries on sensitive tables
#    - Secret retrieval
#    - Credential usage
#    - PII access

# 4. Configuration Changes
#    - Infrastructure modifications
#    - Security policy updates
#    - Encryption key rotation
#    - Backup configuration changes

# 5. System Events
#    - Service restarts
#    - Backup completion
#    - Vulnerability scan results
#    - Compliance check results
```

### Audit Log Query

```nushell
def audit-query [--days: int = 7, --user: string = ""] {
    let start_date = (date now | date add -7d)
    let end_date = (date now)

    let logs = (provisioning audit log \
        --start-date $start_date \
        --end-date $end_date \
        --user $user)

    # Parse and analyze logs
    $logs | each { | log |
        {
            timestamp: $log.timestamp,
            event_type: $log.event_type,
            user: $log.user,
            action: $log.action,
            resource: $log.resource,
            result: $log.result,
            ip_address: $log.ip_address
        }
    } | table
}

# Usage
audit-query --days 30 --user john.doe
```

### Compliance Reports

```bash
# Generate SOC2 compliance report
provisioning compliance report --framework soc2 --period "2025-Q1"
# Output: compliance-soc2-q1-2025.pdf

# Generate GDPR data processing report
provisioning compliance report --framework gdpr --include-dpia
# Output: dpia-report-2025-01.pdf

# Generate PCI-DSS assessment
provisioning compliance report --framework pci-dss --include-remediation
# Output: pci-dss-assessment-2025.pdf

# Generate audit summary
provisioning audit report --summary --period "2025-01-01:2025-01-31"
# Output:
# Total Events Logged: 1,234,567
# Failed Authentications: 23
# Permission Denials: 5
# Data Accesses: 45,123
# Configuration Changes: 234
# Average Response Time: 45ms
```

## Vulnerability Management

```nushell
def scan-for-vulnerabilities [] {
    print "Starting vulnerability scan..."

    # Scan infrastructure
    provisioning security scan --type infrastructure

    # Scan dependencies
    provisioning security scan --type dependencies

    # Scan container images
    provisioning security scan --type containers

    # Generate report
    provisioning security report --output vulnerability-report.pdf
}
```

## Backup and Recovery Testing

```nushell
def test-backup-recovery [--database: string = "production"] {
    print $"Testing backup recovery for ($database)..."

    # Create backup
    let backup_id = (provisioning backup create \
        --database $database \
        --type full \
        --encryption hybrid)

    print $"Backup created: ($backup_id)"

    # Restore to test environment
    let restore_result = (provisioning backup restore \
        --backup-id $backup_id \
        --target-database $"($database)-test" \
        --environment test)

    if $restore_result.status == "success" {
        # Verify data integrity
        let verification = (provisioning database verify \
            --database $"($database)-test" \
            --checksums full)

        if $verification.status == "healthy" {
            print "✓ Backup recovery test successful"
            return 0
        } else {
            print "✗ Data integrity check failed"
            return 1
        }
    } else {
        print "✗ Backup restore failed"
        return 1
    }
}

# Run monthly compliance backup test
schedule {
    every 1 month do {
        test-backup-recovery --database production
    }
}
```

## Change Management

```nushell
def change-request [--description: string, --risk-level: string = "medium"] {
    # Create change ticket
    let change_id = (provisioning change create \
        --description $description \
        --risk-level $risk-level)

    print $"Change request created: ($change_id)"

    # Require approval for high-risk changes
    if $risk-level == "high" {
        print "⚠️  High-risk change requires approval from:"
        print "- Security team"
        print "- Infrastructure lead"
        print "- Compliance officer"

        # Wait for approvals
        let approved = (provisioning change approve \
            --change-id $change_id \
            --wait-for-all)

        if $approved {
            print "✓ Change approved, proceeding..."
        } else {
            print "✗ Change rejected"
            return 1
        }
    }

    return $change_id
}

# Example usage
change-request \
    --description "Add new user to production database" \
    --risk-level "high"
```

## Incident Response

```nushell
def incident-response [--severity: string = "medium"] {
    print $"Initiating incident response (Severity: ($severity))..."

    # Create incident ticket
    let incident_id = (provisioning incident create \
        --severity $severity)

    # Trigger incident response workflow
    provisioning incident trigger \
        --incident-id $incident_id \
        --workflow incident-response-$severity

    # For high severity, escalate
    if $severity == "high" {
        provisioning incident escalate \
            --incident-id $incident_id \
            --notify-slack "#critical-incidents" \
            --notify-pagerduty
    }

    # Automatic mitigation if applicable
    provisioning incident auto-remediate --incident-id $incident_id

    # Collect evidence for audit trail
    provisioning incident collect-evidence \
        --incident-id $incident_id \
        --logs full \
        --metrics "24h"

    return $incident_id
}
```

## Compliance Checklist

- ✅ Encryption at rest (AES-256 with PQC hybrid)
- ✅ Encryption in transit (TLS 1.3)
- ✅ Multi-factor authentication required
- ✅ Audit logging for all events (365-day retention)
- ✅ Regular vulnerability scanning
- ✅ Monthly backup recovery testing
- ✅ Change management process enforced
- ✅ Incident response procedures documented
- ✅ Data residency compliance (EU for GDPR)
- ✅ Network segmentation implemented
- ✅ Access controls with RBAC
- ✅ Automated compliance reporting

## See Also

- [Security System](../features/security-system.md)
- [Data Protection Guide](../security/data-protection.md)
- [Incident Response](../security/incident-response.md)
- [Audit Logging](../security/audit-logging.md)
