<!-- AUTO-GENERATED by export-plugins.py — DO NOT EDIT -->
---
name: cloud-security-patterns
description: Cloud security reference architectures and best practices for GCP, AWS, and Azure
tags: [cloud, security]
---

# Cloud Security Patterns

## Overview

Cloud security operates under a shared responsibility model: the cloud provider secures the infrastructure, while the customer secures their workloads, data, and configurations. Misunderstanding this boundary is the root cause of most cloud security incidents.

This skill provides reference architectures and actionable patterns across five security domains:

| Domain    | Key Concerns                                          |
|-----------|-------------------------------------------------------|
| Identity  | IAM policies, service accounts, workload identity     |
| Network   | VPC design, firewalls, private connectivity, WAF      |
| Data      | Encryption, key management, DLP, data residency       |
| Compute   | Instance hardening, container security, serverless     |
| Logging   | Audit trails, monitoring, alerting, forensics          |

Provider-specific guidance is included for **GCP** (primary for FAOS), **AWS**, and **Azure**, with emphasis on GCP patterns that directly apply to the FAOS platform.

### Shared Responsibility Model

```
+-------------------------+------------------------------------------+
|                         |   Customer Responsibility                |
|  SaaS                   |   Data, access policies, usage config    |
+-------------------------+------------------------------------------+
|  PaaS / Containers      |   Applications, data, access, config     |
|  (GKE, EKS, AKS)       |   Workload security, network policies    |
+-------------------------+------------------------------------------+
|  IaaS                   |   OS, network config, firewall, data     |
|  (GCE, EC2, Azure VMs)  |   Patching, identity, encryption         |
+-------------------------+------------------------------------------+
|  Provider               |   Physical security, hypervisor, global  |
|  Responsibility         |   network, hardware, core services       |
+-------------------------+------------------------------------------+
```

## When to Use This Skill

- You are designing the security architecture for a new cloud deployment
- You are migrating workloads to the cloud and need to establish security controls
- You are reviewing cloud infrastructure code (Terraform, Pulumi) for security issues
- You need to harden an existing GKE, EKS, or AKS cluster
- You are implementing IAM policies and need least-privilege guidance
- You are preparing for a cloud security audit (SOC 2, ISO 27001, CIS)

## How It Works

### Step 1: Classify Workloads

Before applying security controls, classify workloads by sensitivity and exposure:

| Classification | Data Types                     | Security Controls              |
|----------------|--------------------------------|--------------------------------|
| Public         | Marketing content, docs        | Basic: WAF, DDoS protection    |
| Internal       | Business data, internal APIs   | Standard: VPC, IAM, encryption |
| Confidential   | Customer PII, financial data   | Enhanced: CMEK, DLP, audit logs|
| Restricted     | Secrets, keys, auth tokens     | Maximum: HSM, dedicated tenancy|

This classification drives decisions for network isolation, encryption, access control, and monitoring.

### Step 2: Design Network Boundaries

Implement defense-in-depth through network segmentation:

```
Internet
    |
[Cloud Load Balancer + WAF + Cloud Armor]
    |
[Public Subnet / DMZ]
    |--- Web tier (frontend, API gateway)
    |
[Private Subnet]
    |--- Application tier (GKE, compute)
    |--- Service mesh (mTLS between services)
    |
[Restricted Subnet]
    |--- Data tier (Cloud SQL, Redis, storage)
    |--- No internet access, VPC-SC perimeter
```

Key network security patterns:

- **Private GKE clusters**: Control plane and nodes have no public IPs
- **VPC Service Controls**: Create security perimeters around GCP services to prevent data exfiltration
- **Private Google Access**: Reach Google APIs without traversing the public internet
- **Cloud NAT**: Controlled egress for private instances that need internet access
- **Firewall rules**: Default-deny ingress, explicit allow rules with source filtering

### Step 3: Implement IAM Policies

IAM is the most critical security control in cloud environments. A misconfigured IAM policy can expose an entire organization.

**Principle of Least Privilege:**

```
# GCP: Grant minimum required roles
# BAD - overly broad
gcloud projects add-iam-policy-binding $PROJECT \
  --member="serviceAccount:app-sa@$PROJECT.iam.gserviceaccount.com" \
  --role="roles/editor"

# GOOD - specific to need
gcloud projects add-iam-policy-binding $PROJECT \
  --member="serviceAccount:app-sa@$PROJECT.iam.gserviceaccount.com" \
  --role="roles/cloudsql.client"
```

**Service Account Patterns:**

| Pattern                | Use Case                           | Security Level |
|------------------------|------------------------------------|----------------|
| Workload Identity      | GKE pods accessing GCP services    | Highest        |
| Attached SA            | GCE instances with scoped roles    | High           |
| SA Key (JSON)          | External systems (avoid if possible)| Medium        |
| User credentials       | Development only                   | Low            |

### Step 4: Enable Encryption

Encryption must cover data at rest and in transit:

**At Rest:**
- **Default encryption**: All major cloud providers encrypt data at rest by default
- **CMEK (Customer-Managed Encryption Keys)**: Use Cloud KMS to control key lifecycle
- **CSEK (Customer-Supplied Encryption Keys)**: You manage keys entirely outside the cloud provider

**In Transit:**
- **TLS 1.2+**: All service-to-service communication
- **mTLS**: Service mesh (Istio/Anthos) for mutual authentication between microservices
- **VPN/Interconnect**: Encrypted connectivity between on-premises and cloud

```bash
# GCP: Create a CMEK key ring and key
gcloud kms keyrings create faos-keyring --location=global
gcloud kms keys create faos-data-key \
  --location=global \
  --keyring=faos-keyring \
  --purpose=encryption \
  --rotation-period=90d \
  --next-rotation-time=$(date -u -d "+90 days" +%Y-%m-%dT%H:%M:%SZ)
```

### Step 5: Configure Logging and Monitoring

Comprehensive logging is non-negotiable for security operations and compliance:

| Log Type                | GCP Service          | AWS Equivalent      | Purpose                    |
|-------------------------|----------------------|---------------------|----------------------------|
| Admin Activity          | Cloud Audit Logs     | CloudTrail          | Who changed what           |
| Data Access             | Cloud Audit Logs     | CloudTrail Data     | Who accessed what data     |
| Network Flows           | VPC Flow Logs        | VPC Flow Logs       | Network traffic analysis   |
| Application Logs        | Cloud Logging        | CloudWatch Logs     | App-level events           |
| Container Logs          | GKE Logging          | EKS/CloudWatch      | Container stdout/stderr    |
| DNS Queries             | Cloud DNS Logging    | Route 53 Query Logs | DNS-based threat detection |

Enable alert policies for critical events:

```yaml
# GCP Monitoring alert for IAM policy changes
alertPolicy:
  displayName: "IAM Policy Modification"
  conditions:
    - displayName: "IAM policy changed"
      conditionMatchedLog:
        filter: |
          protoPayload.methodName=("SetIamPolicy" OR "UpdateIamPolicy")
          AND protoPayload.serviceName!="k8s.io"
        labelExtractors:
          principal: "EXTRACT(protoPayload.authenticationInfo.principalEmail)"
  notificationChannels:
    - projects/my-gcp-project/notificationChannels/security-team
  alertStrategy:
    autoClose: 604800s  # 7 days
```

## Examples

### Example 1: GKE Private Cluster with Workload Identity

This configuration demonstrates GCP security best practices:

```hcl
# Terraform: Private GKE cluster with Workload Identity
resource "google_container_cluster" "faos_cluster" {
  name     = "my-gke-cluster"
  location = "asia-southeast1-a"
  project  = "my-gcp-project"

  # Private cluster configuration
  private_cluster_config {
    enable_private_nodes    = true
    enable_private_endpoint = false  # Allow kubectl from authorized networks
    master_ipv4_cidr_block  = "172.16.0.0/28"
  }

  # Authorized networks for API server access
  master_authorized_networks_config {
    cidr_blocks {
      cidr_block   = "10.0.0.0/8"
      display_name = "Internal VPC"
    }
  }

  # Workload Identity for keyless service account access
  workload_identity_config {
    workload_pool = "my-gcp-project.svc.id.goog"
  }

  # Binary Authorization for image verification
  binary_authorization {
    evaluation_mode = "PROJECT_SINGLETON_POLICY"
  }

  # Network policy enforcement
  network_policy {
    enabled  = true
    provider = "CALICO"
  }

  # Shielded GKE nodes
  node_config {
    shielded_instance_config {
      enable_secure_boot          = true
      enable_integrity_monitoring = true
    }

    workload_metadata_config {
      mode = "GKE_METADATA"  # Enables Workload Identity on nodes
    }

    # Use COS-containerd for security
    image_type = "COS_CONTAINERD"

    # Service account with minimal permissions
    service_account = google_service_account.gke_node_sa.email
    oauth_scopes    = ["https://www.googleapis.com/auth/cloud-platform"]
  }

  # Enable logging and monitoring
  logging_config {
    enable_components = ["SYSTEM_COMPONENTS", "WORKLOADS"]
  }
  monitoring_config {
    enable_components = ["SYSTEM_COMPONENTS"]
    managed_prometheus { enabled = true }
  }
}

# Workload Identity binding for application service account
resource "google_service_account" "app_sa" {
  account_id   = "my-app-sa"
  display_name = "FAOS API Service Account"
  project      = "my-gcp-project"
}

resource "google_service_account_iam_binding" "workload_identity" {
  service_account_id = google_service_account.app_sa.name
  role               = "roles/iam.workloadIdentityUser"
  members = [
    "serviceAccount:my-gcp-project.svc.id.goog[my-namespace/my-app-sa]"
  ]
}

# Kubernetes ServiceAccount annotation for Workload Identity
resource "kubernetes_service_account" "app_sa" {
  metadata {
    name      = "my-app-sa"
    namespace = "faos-api"
    annotations = {
      "iam.gke.io/gcp-service-account" = google_service_account.app_sa.email
    }
  }
}
```

### Example 2: GCP IAM Policy for Least-Privilege Service Accounts

```bash
#!/bin/bash
# create-least-privilege-sa.sh
# Creates service accounts with minimum required permissions for FAOS components

PROJECT="my-gcp-project"

# API service account: needs Cloud SQL, Secret Manager, Cloud Storage
gcloud iam service-accounts create my-app-sa \
  --display-name="FAOS API Service Account" \
  --project=$PROJECT

# Grant only specific roles (never roles/editor or roles/owner)
declare -A API_ROLES=(
  ["roles/cloudsql.client"]="Connect to Cloud SQL instances"
  ["roles/secretmanager.secretAccessor"]="Read secrets"
  ["roles/storage.objectViewer"]="Read from Cloud Storage buckets"
  ["roles/logging.logWriter"]="Write application logs"
  ["roles/monitoring.metricWriter"]="Write custom metrics"
)

for role in "${!API_ROLES[@]}"; do
  echo "Granting ${role}: ${API_ROLES[$role]}"
  gcloud projects add-iam-policy-binding $PROJECT \
    --member="serviceAccount:my-app-sa@${PROJECT}.iam.gserviceaccount.com" \
    --role="$role" \
    --condition=None
done

# Worker service account: needs Pub/Sub, Cloud Tasks, limited Cloud SQL
gcloud iam service-accounts create faos-worker-sa \
  --display-name="FAOS Worker Service Account" \
  --project=$PROJECT

declare -A WORKER_ROLES=(
  ["roles/pubsub.subscriber"]="Consume messages from Pub/Sub"
  ["roles/pubsub.publisher"]="Publish messages to Pub/Sub"
  ["roles/cloudtasks.enqueuer"]="Enqueue Cloud Tasks"
  ["roles/cloudsql.client"]="Connect to Cloud SQL"
  ["roles/logging.logWriter"]="Write application logs"
)

for role in "${!WORKER_ROLES[@]}"; do
  echo "Granting ${role}: ${WORKER_ROLES[$role]}"
  gcloud projects add-iam-policy-binding $PROJECT \
    --member="serviceAccount:faos-worker-sa@${PROJECT}.iam.gserviceaccount.com" \
    --role="$role" \
    --condition=None
done

# Verify: list roles for each service account
echo "=== API SA Roles ==="
gcloud projects get-iam-policy $PROJECT \
  --flatten="bindings[].members" \
  --filter="bindings.members:my-app-sa@" \
  --format="table(bindings.role)"

echo "=== Worker SA Roles ==="
gcloud projects get-iam-policy $PROJECT \
  --flatten="bindings[].members" \
  --filter="bindings.members:faos-worker-sa@" \
  --format="table(bindings.role)"
```

## Best Practices

### Do This

- Use Workload Identity (GKE), IRSA (EKS), or Managed Identity (AKS) instead of service account keys
- Enable VPC Service Controls for all services handling sensitive data
- Implement network segmentation with private subnets and explicit firewall rules
- Use Cloud KMS with automatic key rotation for customer-managed encryption keys
- Enable all audit log types: Admin Activity, Data Access, System Events
- Apply the principle of least privilege to every service account and IAM binding
- Use Binary Authorization to enforce that only verified images run in production
- Implement Cloud Armor or AWS WAF for public-facing endpoints
- Set organization policy constraints to prevent common misconfigurations
- Use infrastructure as code (Terraform) for all security configurations to ensure reproducibility

### Don't Do This

- Do not use primitive roles (Owner, Editor, Viewer) -- use predefined or custom roles
- Do not create service account keys unless absolutely necessary (prefer Workload Identity)
- Do not expose GKE API server to the public internet without authorized networks
- Do not disable audit logging to reduce costs -- it is essential for incident response
- Do not use default VPC networks -- create purpose-built VPCs with proper CIDR planning
- Do not store secrets in environment variables, ConfigMaps, or source code
- Do not grant `allUsers` or `allAuthenticatedUsers` access to cloud resources
- Do not skip VPC Flow Logs -- they are critical for network forensics
- Do not use self-signed certificates for production services
- Do not ignore Cloud Security Command Center findings

## Security Checklist

### Identity and Access

- [ ] No primitive roles (Owner, Editor, Viewer) assigned to service accounts
- [ ] Workload Identity is enabled for all GKE pods accessing GCP services
- [ ] Service account keys are not used (or have rotation policies if unavoidable)
- [ ] MFA is enforced for all human accounts accessing cloud consoles
- [ ] IAM conditions are used for time-based or resource-based access restrictions
- [ ] Regular access reviews are conducted (quarterly minimum)
- [ ] Organization policy constraints prevent public resource creation

### Network Security

- [ ] GKE clusters are private (no public node IPs)
- [ ] VPC Service Controls perimeters protect sensitive services
- [ ] Default-deny firewall rules are in place with explicit allow rules
- [ ] Private Google Access is enabled for private subnets
- [ ] Cloud NAT provides controlled egress for private resources
- [ ] Cloud Armor / WAF protects public-facing endpoints
- [ ] DNS logging is enabled for threat detection

### Data Protection

- [ ] Customer-managed encryption keys (CMEK) are configured for sensitive data stores
- [ ] KMS key rotation is enabled (90-day rotation recommended)
- [ ] TLS 1.2+ is enforced for all external and internal connections
- [ ] mTLS is enabled between microservices via service mesh
- [ ] Data Loss Prevention (DLP) scanning is enabled for sensitive data stores
- [ ] Backup encryption uses separate keys from production data

### Logging and Monitoring

- [ ] Admin Activity audit logs are enabled (on by default, cannot be disabled)
- [ ] Data Access audit logs are enabled for all sensitive services
- [ ] VPC Flow Logs are enabled for all subnets
- [ ] Log sinks export logs to a separate project for tamper resistance
- [ ] Alert policies are configured for critical security events
- [ ] Security Command Center is enabled with Premium tier
- [ ] Log retention meets compliance requirements (minimum 90 days, 1 year recommended)

## Related Skills

- @cis-benchmarks -- CIS Benchmark automated scanning for GKE, Docker, and GCP
- @container-security-guide -- detailed Docker and Kubernetes runtime hardening
- @nist-csf -- mapping cloud security controls to NIST Cybersecurity Framework

## Additional Resources

- [GCP Security Best Practices](https://cloud.google.com/security/best-practices) -- official Google Cloud security guidance
- [GCP Architecture Framework: Security](https://cloud.google.com/architecture/framework/security) -- security pillar of the architecture framework
- [AWS Well-Architected Security Pillar](https://docs.aws.amazon.com/wellarchitected/latest/security-pillar/) -- AWS security reference
- [Azure Security Benchmark](https://learn.microsoft.com/en-us/security/benchmark/azure/) -- Microsoft security guidance
- [GKE Hardening Guide](https://cloud.google.com/kubernetes-engine/docs/how-to/hardening-your-cluster) -- GKE-specific security recommendations
- [NIST SP 800-210](https://csrc.nist.gov/publications/detail/sp/800-210/final) -- General Access Control Guidance for Cloud Systems

<!-- Source: .faos/custom/skills/security/cloud-security-patterns/SKILL.md -->
