WATCHMEN v0.9.0 // OPERATOR MANUAL & DEPLOYMENT GUIDE

Complete Feature Manual & Multi-Cloud Terraform

Every capability in Watchmen — from multi-cloud posture scanning and SOC 2 / ISO 27001 compliance to runtime HTTP 403 enforcement, CLI/MCP task handoff, and production Terraform templates for AWS, GCP, and Azure.

01 // CORE/dashboard & /dashboard/settings

Architecture, Auth & AI Keys

Watchmen v0.9.0 is a self-hosted cloud security posture, compliance, live request tracing, and runtime enforcement console for AWS, GCP, and Kubernetes.

  • $Per-user OAuth & encrypted cloud credentials (AES-256-GCM using AUTH_SECRET).
  • $Bring-your-own AI key: Google Gemini, Anthropic Claude, or OpenAI validated live and encrypted per user in PostgreSQL.
  • $Three auth modes: Google OAuth (with ALLOWED_EMAILS / ALLOWED_DOMAIN allowlists), Local Auth, and one-click Demo Mode.
  • $PostgreSQL persistence using @neondatabase/serverless (pooled) and pg (direct) with auto-migrated tables.
ShortcutActionRoute / Target
/Focus Natural Language BrainQuery box on dashboard
⌘K / Ctrl+KGlobal Command Palette & SearchAny page or resource
G / ASwitch GCP / AWS Overview/dashboard, /dashboard/aws
F / P / CFindings / Attack Paths / Compliance/dashboard/findings, /attack-paths, /compliance
R / T / STrace / Tasks / Settings/dashboard/trace, /tasks, /settings
?Keyboard Shortcuts Help ModalGlobal overlay
02 // INVENTORY/dashboard & /dashboard/aws

Multi-Cloud Scanning & Natural Language Brain

Snapshot-based cloud scanning fetches your GCP and AWS inventory once, caches it in PostgreSQL JSONB, and powers instant queries without repeated cloud API calls.

  • $GCP (12 services): IAM bindings, Service Accounts & keys, GKE clusters, Cloud SQL, Cloud Run, Storage Buckets, BigQuery, Pub/Sub, Secret Manager, VMs, Firewall Rules, Cloud Logging.
  • $GCP Keyless ADC: Automatically uses Application Default Credentials (Workload Identity / Cloud Run SA) when no user OAuth token or JSON key is stored.
  • $AWS (11 services): IAM Users & Roles, EC2 instances, Security Groups, S3 Buckets, RDS, Redshift, Lambda, EKS, Secrets Manager, SNS, ECR & CloudTrail.
  • $Natural Language Brain: Ask plain-English questions (e.g. 'Which buckets are public?' or 'Who has roles/owner across projects?') and click returned resource chips.
  • $Scan Coverage (/dashboard/scan-coverage) & Snapshot History (/dashboard/history) track partial permissions and historical posture changes.
03 // POSTURE/dashboard/findings

Security Findings, Agentic Workflows & Terraform PRs

Pure-function security rules rank misconfigurations by severity (Critical, High, Medium, Low) across GCP and AWS, backed by audited AI investigation, planning, fix verification, and GitHub PR automation.

  • $12 GCP rules + 8 AWS rules covering public buckets, 0.0.0.0/0 firewall/SG rules, expired SA keys, overly permissive IAM roles, unencrypted databases, and exposed env-var secrets.
  • $Watchlist & Filters: Pin priority findings, filter by cloud (GCP/AWS) or severity, search across resources, and export CSV/JSON.
  • $Audited Agent Runs: Investigate Finding → Plan Remediation (approval-gated) → Create Terraform PR → Verify Fix against fresh snapshots.
  • $Terraform GitHub PR Remediation: Scans your linked GitHub repository for matching .tf files, generates least-privilege patches, preserves originals, opens a PR, and notifies Slack.
  • $CLI & MCP Handoff: Send individual findings (with their investigation & plan reports) or all filtered findings directly to OpenCode, Claude Code, or Codex.
04 // GRAPH/dashboard/attack-paths

Attack Path Analysis

Correlates standalone misconfigurations into multi-step exploit chains (Entry → Pivot → Target) across GCP and AWS so teams can break high-risk chains first.

  • $Detects chains like Internet → Open Firewall → Compute VM → Privileged Service Account → Project/Data Access.
  • $Interactive path cards with clickable resource nodes, AI remediation advice, direct Terraform PR generation for GCP paths, and Send to CLI handoff.
05 // AUDIT/dashboard/compliance

Compliance Engine (SOC 2 Type II & ISO 27001:2022)

Automated 18-control SOC 2 Type II and ISO 27001:2022 evaluations across GCP and AWS with score trending, risk acceptances, auditor exports, and CLI/MCP remediation handoff.

  • $Multi-cloud scoring (pass = 1, suppressed = 1, warning = 0.5, fail = 0) with per-project violation breakdown and historical score trend SVG chart.
  • $Risk Acceptance (Suppressions): Suppress individual controls with written audit justification and revoke at any time.
  • $Auditor Exports: Download CSV evidence reports or print/save formatted PDF reports.
  • $AI Control Advice & Send to CLI: Ask AI for per-control remediation guidance, or push failing/warning controls (along with AI advice) straight to OpenCode, Claude Code, or Codex.
06 // WORKLOADS/dashboard/container-scan & /dashboard/self-managed

Container Scanning, Self-Managed K8s & eBPF Agent

Scan container images across cloud and public registries and monitor any self-managed Kubernetes cluster alongside GKE and EKS.

  • $Container Vulnerability Scanning: GCP Artifact Registry/GCR, AWS ECR, GitHub Container Registry (GHCR), and Docker Hub CVE inspection with AI upgrade recommendations.
  • $Self-Managed Kubernetes: Upload single or merged kubeconfigs (k3s, kind, minikube, k0s, microk8s, RKE2, Talos, on-prem) — each context is scanned, traced, and queried independently.
  • $eBPF DaemonSet & VM Agent: Captures kernel-level L4 socket tuples + HTTP request/response events without spoofable L7 headers, with automatic secret & query-param redaction.
07 // RUNTIME/dashboard/trace & /dashboard/runtime

Live Request Tracing & Runtime Enforcement (v0.9)

Stream real-time HTTP traffic onto an animated service topology and enforce detect-or-block runtime policies via inline proxy/trace gates and the v1 REST API.

  • $Live Trace Topology: Ingests traffic from Cloud Logging Pub/Sub push (/api/ingest/gcp/pubsub), eBPF agents (/api/agents/events), /api/proxy, and /api/trace over SSE (/api/trace/live).
  • $Global Source Map: Interactive MapLibre 3D globe + SVG fallback with resizable pane, time-window filters, and IP geolocation.
  • $Runtime Policy Engine (Detect & Enforce): Rules support alert/block actions, mode: detect | enforce, HTTP 403 blocking in /api/proxy and /api/trace, and decisions allow | flagged | would_block | blocked.
  • $Attack Vector Templates & Conditions: method, path_prefix, path_regex, content_type, body_contains, source_ip_class, status_code, plus 6 built-in known_attack_vector templates (admin_path_probe, path_traversal, sql_injection_probe, rce_probe, sensitive_file_probe, destructive_method).
Watchmen v1 Runtime REST API (Bearer wm_...)
# Create an enforce-mode block rule for admin probes
curl -X POST https://your-watchmen-url/api/watchmen/v1/runtime/rules \
  -H "Authorization: Bearer $WATCHMEN_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Block admin paths",
    "action": "block",
    "mode": "enforce",
    "severity": "critical",
    "condition": { "kind": "path_prefix", "value": "/admin" }
  }'

# Query blocked requests & runtime summary
curl -H "Authorization: Bearer $WATCHMEN_API_TOKEN" \
  "https://your-watchmen-url/api/watchmen/v1/runtime/requests?decision=blocked"
curl -H "Authorization: Bearer $WATCHMEN_API_TOKEN" \
  "https://your-watchmen-url/api/watchmen/v1/runtime/summary"
08 // AGENTIC CLI/dashboard/tasks & /dashboard/settings

CLI & MCP Task Handoff (OpenCode, Claude Code, Codex)

Push findings, attack paths, and failing compliance controls from Watchmen into open tasks for local AI coding CLIs, complete with MCP integration, isolated git worktrees, and closed-loop verification.

  • $Send to CLI Modal: Available on Findings, Attack Paths, and Compliance. Groups issues by category (IAM, Firewall, Storage, etc.), combines them, or splits 1-per-issue, with automatic secret redaction and deduplication.
  • $Watchmen MCP Server: Remote Streamable HTTP endpoint at /api/mcp and zero-dependency local stdio bridge (node scripts/watchmen-mcp.mjs) exposing 8 tools for task handoff and runtime security queries.
  • $Local Runner & Watcher (scripts/watchmen-cli.mjs): Poll or execute tasks via OpenCode, Claude Code, Codex, or custom commands inside isolated .watchmen-worktrees/<taskId> git branches.
  • $Closed-Loop Verification: POST /api/handoff/tasks/:id/verify (or watchmen_verify_task MCP tool) re-checks findings, attack paths, and compliance controls against latest snapshots and auto-completes resolved tasks.
Connect OpenCode / Claude / Codex via MCP & Run Locally
# 1. Export Personal API Token (generated in Settings -> Integrations)
export WATCHMEN_API_TOKEN="wm_your_token_here"
export WATCHMEN_URL="https://your-watchmen-url"

# 2. Claude Code HTTP MCP setup
claude mcp add --transport http watchmen \
  "$WATCHMEN_URL/api/mcp" \
  --header "Authorization: Bearer $WATCHMEN_API_TOKEN"

# 3. Or auto-run open Watchmen tasks in isolated git worktrees
node scripts/watchmen-cli.mjs watch --tool opencode --worktree --verify --once
09 // ALERTS/dashboard/settings

Alerting & Integrations

Configure Slack Bot or generic webhook notifications whenever cloud scans uncover new Critical or High findings, or when Terraform remediation PRs are opened.

  • $Slack Bot & Webhook delivery with test and simulate endpoints (/api/alerts/test, /api/alerts/simulate).
  • $Automatic evaluation on new scans (/api/alerts/evaluate) tracking previously seen finding IDs to prevent repeat alert fatigue.

10 // DEPLOYMENT GUIDE

Every Way to Deploy Watchmen

Deploy on Vercel, Docker, Kubernetes, or provision full cloud infrastructure on AWS, GCP, or Azure using the Terraform templates below.

FASTEST // SERVERLESS

Vercel + Neon Postgres

Best for: Zero-ops production hosting with serverless Postgres

Deploy the Next.js app directly to Vercel and attach a Neon Postgres integration. Watchmen uses @neondatabase/serverless for pooled connections automatically.

  1. 1.Fork or import pavelzag/watchmen in Vercel.
  2. 2.Add Neon Postgres from the Vercel Marketplace (sets POSTGRES_URL).
  3. 3.Configure AUTH_SECRET, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, and ALLOWED_EMAILS / ALLOWED_DOMAIN.
  4. 4.Run psql $POSTGRES_URL < scripts/migrate.sql (or let Watchmen auto-create tables on first request).
vercel
npx vercel login
npx vercel link
psql "$POSTGRES_URL" < scripts/migrate.sql
npx vercel --prod
SELF-HOSTED // CONTAINER

Docker & Docker Compose

Best for: Single VM, bare-metal servers, or local air-gapped networks

Use the multi-arch container image published to GitHub Container Registry (linux/amd64 and linux/arm64) backed by any PostgreSQL 14+ instance.

  1. 1.Copy .env.local.example to .env.local and set POSTGRES_URL, AUTH_SECRET, and AUTH_TRUST_HOST=true.
  2. 2.Pull ghcr.io/pavelzag/watchmen:latest or build locally from Dockerfile (Node 22 Alpine standalone).
  3. 3.Run PostgreSQL + Watchmen container on port 3000.
docker
docker pull ghcr.io/pavelzag/watchmen:latest
docker run -d --name watchmen \
  -p 3000:3000 \
  --env-file .env.local \
  ghcr.io/pavelzag/watchmen:latest
CLUSTER // FULL STACK

Kubernetes (GKE / EKS / AKS / Self-Managed)

Best for: Teams running the full stack + eBPF DaemonSet + Go trace processor

Deploy Watchmen as a Deployment behind Ingress with TLS, mount secrets from Kubernetes Secrets, and optionally run services/request-processor and the eBPF DaemonSet.

  1. 1.Create namespace watchmen and secret watchmen-secrets containing POSTGRES_URL, AUTH_SECRET, and OAuth credentials.
  2. 2.Apply Deployment (image ghcr.io/pavelzag/watchmen:latest, port 3000, /api/health readiness probe) + Service + Ingress.
  3. 3.Optionally deploy services/ebpf-agent DaemonSet or register the cluster in Settings -> Self-Managed Kubernetes.
kubernetes
kubectl create namespace watchmen
kubectl -n watchmen create secret generic watchmen-secrets \
  --from-literal=POSTGRES_URL="postgresql://user:pass@postgres:5432/watchmen" \
  --from-literal=AUTH_SECRET="$(openssl rand -base64 32)" \
  --from-literal=AUTH_TRUST_HOST="true"
kubectl -n watchmen create deployment watchmen --image=ghcr.io/pavelzag/watchmen:latest --port=3000
kubectl -n watchmen expose deployment watchmen --port=80 --target-port=3000
DEV // SANDBOX

Local Development & Demo Mode

Best for: Evaluation without cloud credentials or OAuth setup

Run Watchmen locally in 60 seconds using fixture data (DEMO_MODE=true, USE_MOCK_DATA=true) or connect real cloud credentials in Settings.

  1. 1.Clone pavelzag/watchmen and run npm install.
  2. 2.Set DEMO_MODE=true, USE_MOCK_DATA=true, AUTH_SECRET, and AUTH_TRUST_HOST=true in .env.local.
  3. 3.Run npm run dev and sign in with Enter Demo.
local-demo
git clone git@github.com:pavelzag/watchmen.git
cd watchmen && npm install
cp .env.local.example .env.local
npm run dev

Environment Variables & Database Migration

Tables auto-initialize on first request, or you can apply the schema ahead of time with psql $POSTGRES_URL < scripts/migrate.sql.

VariableRequiredPurpose
POSTGRES_URLYes (non-demo)PostgreSQL connection string (Neon, Cloud SQL, RDS, Azure PG, or local)
AUTH_SECRETYesNextAuth + AES-256-GCM encryption secret (openssl rand -base64 32)
AUTH_TRUST_HOSTDocker / ProxySet to true behind ALBs, Ingress, Cloud Run, or custom domains
GOOGLE_CLIENT_ID / SECRETOAuth modeGoogle OAuth 2.0 Web App credentials with cloud-platform scope
ALLOWED_EMAILS / DOMAINOAuth modeComma-separated allowlist emails or Google Workspace domain
DEMO_MODE / USE_MOCK_DATAOptionalSet true for fixture sandbox mode with one-click demo login
GCP_PROJECTS / GCP_ORG_IDOptionalTarget GCP project IDs or Org ID for background/ADC scans
PROCESSOR_URLOptionalInternal URL for services/request-processor trace backend

11 // MULTI-CLOUD TERRAFORM BUNDLES

Deploy on AWS, GCP, or Azure with Terraform

Download or curl the ready-to-apply Terraform files directly from Watchmen Web. Each bundle provisions Watchmen, managed PostgreSQL 16, secret storage, and a scoped read-only cloud identity.

Full-Stack Watchmen Deployments

Scanner-Only Credentials (for Vercel / Local Watchmen)

AWS (ECS Fargate + RDS + ALB)

Application Load Balancer (HTTP/HTTPS) -> ECS Fargate (ghcr.io/pavelzag/watchmen:latest) + Secrets Manager + encrypted RDS PostgreSQL 16 + ReadOnlyAccess IAM Task Role.

  • Terraform >= 1.6 and AWS CLI authenticated (aws sts get-caller-identity).
  • Default VPC available in target region (or adapt data.aws_vpc.default).
fetch & apply (aws)
mkdir -p watchmen-aws && cd watchmen-aws
curl -fsSLO https://watchmen-web-six.vercel.app/terraform/aws/main.tf
curl -fsSLO https://watchmen-web-six.vercel.app/terraform/aws/variables.tf
curl -fsSLO https://watchmen-web-six.vercel.app/terraform/aws/outputs.tf
curl -fsSLO https://watchmen-web-six.vercel.app/terraform/aws/terraform.tfvars.example
cp terraform.tfvars.example terraform.tfvars
# Edit terraform.tfvars with AUTH_SECRET & Google OAuth values
terraform init && terraform apply
public/terraform/aws/main.tf
terraform {
  required_version = ">= 1.6.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
    random = {
      source  = "hashicorp/random"
      version = "~> 3.6"
    }
  }
}

provider "aws" {
  region = var.aws_region
}

data "aws_vpc" "default" {
  default = true
}

data "aws_subnets" "default" {
  filter {
    name   = "vpc-id"
    values = [data.aws_vpc.default.id]
  }
}

resource "random_password" "db_password" {
  count   = var.db_password == "" ? 1 : 0
  length  = 24
  special = false
}

locals {
  effective_db_password = var.db_password != "" ? var.db_password : random_password.db_password[0].result
}

# ── Networking & Security Groups ──────────────────────────────────────────────

resource "aws_security_group" "alb" {
  name        = "${var.app_name}-alb-sg"
  description = "Allow HTTP/HTTPS inbound to Watchmen ALB"
  vpc_id      = data.aws_vpc.default.id

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  dynamic "ingress" {
    for_each = var.certificate_arn != "" ? [1] : []
    content {
      from_port   = 443
      to_port     = 443
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    }
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_security_group" "ecs" {
  name        = "${var.app_name}-ecs-sg"
  description = "Allow traffic from ALB to Watchmen ECS tasks"
  vpc_id      = data.aws_vpc.default.id

  ingress {
    from_port       = 3000
    to_port         = 3000
    protocol        = "tcp"
    security_groups = [aws_security_group.alb.id]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_security_group" "rds" {
  name        = "${var.app_name}-rds-sg"
  description = "Allow PostgreSQL traffic from Watchmen ECS tasks"
  vpc_id      = data.aws_vpc.default.id

  ingress {
    from_port       = 5432
    to_port         = 5432
    protocol        = "tcp"
    security_groups = [aws_security_group.ecs.id]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

# ── RDS PostgreSQL ────────────────────────────────────────────────────────────

resource "aws_db_subnet_group" "watchmen" {
  name       = "${var.app_name}-db-subnet-group"
  subnet_ids = data.aws_subnets.default.ids
}

resource "aws_db_instance" "watchmen" {
  identifier             = "${var.app_name}-postgres"
  engine                 = "postgres"
  engine_version         = "16.4"
  instance_class         = var.db_instance_class
  allocated_storage      = 20
  storage_encrypted      = true
  db_name                = "watchmen"
  username               = var.db_username
  password               = local.effective_db_password
  db_subnet_group_name   = aws_db_subnet_group.watchmen.name
  vpc_security_group_ids = [aws_security_group.rds.id]
  skip_final_snapshot    = true
  publicly_accessible    = false
}

# ── Secrets Manager ───────────────────────────────────────────────────────────

resource "aws_secretsmanager_secret" "postgres_url" {
  name                    = "${var.app_name}/postgres-url"
  recovery_window_in_days = 0
}

resource "aws_secretsmanager_secret_version" "postgres_url" {
  secret_id     = aws_secretsmanager_secret.postgres_url.id
  secret_string = "postgresql://${var.db_username}:${local.effective_db_password}@${aws_db_instance.watchmen.endpoint}/watchmen?sslmode=require"
}

resource "aws_secretsmanager_secret" "auth_secret" {
  name                    = "${var.app_name}/auth-secret"
  recovery_window_in_days = 0
}

resource "aws_secretsmanager_secret_version" "auth_secret" {
  secret_id     = aws_secretsmanager_secret.auth_secret.id
  secret_string = var.auth_secret
}

resource "aws_secretsmanager_secret" "google_client_secret" {
  name                    = "${var.app_name}/google-client-secret"
  recovery_window_in_days = 0
}

resource "aws_secretsmanager_secret_version" "google_client_secret" {
  secret_id     = aws_secretsmanager_secret.google_client_secret.id
  secret_string = var.google_client_secret
}

# ── IAM Roles (Execution, Task, and Read-Only AWS Scanner) ────────────────────

data "aws_iam_policy_document" "ecs_assume" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "Service"
      identifiers = ["ecs-tasks.amazonaws.com"]
    }
  }
}

resource "aws_iam_role" "ecs_execution" {
  name               = "${var.app_name}-ecs-execution-role"
  assume_role_policy = data.aws_iam_policy_document.ecs_assume.json
}

resource "aws_iam_role_policy_attachment" "ecs_execution_managed" {
  role       = aws_iam_role.ecs_execution.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
}

resource "aws_iam_role_policy" "ecs_execution_secrets" {
  name = "${var.app_name}-read-secrets"
  role = aws_iam_role.ecs_execution.id

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect = "Allow"
        Action = ["secretsmanager:GetSecretValue"]
        Resource = [
          aws_secretsmanager_secret.postgres_url.arn,
          aws_secretsmanager_secret.auth_secret.arn,
          aws_secretsmanager_secret.google_client_secret.arn,
        ]
      }
    ]
  })
}

resource "aws_iam_role" "ecs_task" {
  name               = "${var.app_name}-ecs-task-role"
  assume_role_policy = data.aws_iam_policy_document.ecs_assume.json
}

resource "aws_iam_role_policy_attachment" "scanner_readonly" {
  role       = aws_iam_role.ecs_task.name
  policy_arn = "arn:aws:iam::aws:policy/ReadOnlyAccess"
}

# ── ECS Cluster, ALB & Fargate Service ────────────────────────────────────────

resource "aws_cloudwatch_log_group" "watchmen" {
  name              = "/ecs/${var.app_name}"
  retention_in_days = 14
}

resource "aws_ecs_cluster" "watchmen" {
  name = "${var.app_name}-cluster"
}

resource "aws_lb" "watchmen" {
  name               = "${var.app_name}-alb"
  internal           = false
  load_balancer_type = "application"
  security_groups    = [aws_security_group.alb.id]
  subnets            = data.aws_subnets.default.ids
}

resource "aws_lb_target_group" "watchmen" {
  name        = "${var.app_name}-tg"
  port        = 3000
  protocol    = "HTTP"
  vpc_id      = data.aws_vpc.default.id
  target_type = "ip"

  health_check {
    path                = "/api/health"
    healthy_threshold   = 2
    unhealthy_threshold = 3
    interval            = 30
  }
}

resource "aws_lb_listener" "http" {
  load_balancer_arn = aws_lb.watchmen.arn
  port              = 80
  protocol          = "HTTP"

  default_action {
    type             = var.certificate_arn != "" ? "redirect" : "forward"
    target_group_arn = var.certificate_arn != "" ? null : aws_lb_target_group.watchmen.arn

    dynamic "redirect" {
      for_each = var.certificate_arn != "" ? [1] : []
      content {
        port        = "443"
        protocol    = "HTTPS"
        status_code = "HTTP_301"
      }
    }
  }
}

resource "aws_lb_listener" "https" {
  count             = var.certificate_arn != "" ? 1 : 0
  load_balancer_arn = aws_lb.watchmen.arn
  port              = 443
  protocol          = "HTTPS"
  ssl_policy        = "ELBSecurityPolicy-TLS13-1-2-2021-06"
  certificate_arn   = var.certificate_arn

  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.watchmen.arn
  }
}

resource "aws_ecs_task_definition" "watchmen" {
  family                   = var.app_name
  requires_compatibilities = ["FARGATE"]
  network_mode             = "awsvpc"
  cpu                      = "1024"
  memory                   = "2048"
  execution_role_arn       = aws_iam_role.ecs_execution.arn
  task_role_arn            = aws_iam_role.ecs_task.arn

  container_definitions = jsonencode([
    {
      name      = "watchmen"
      image     = var.watchmen_image
      essential = true
      portMappings = [
        {
          containerPort = 3000
          protocol      = "tcp"
        }
      ]
      environment = [
        { name = "NODE_ENV", value = "production" },
        { name = "PORT", value = "3000" },
        { name = "GOOGLE_CLIENT_ID", value = var.google_client_id },
        { name = "ALLOWED_EMAILS", value = var.allowed_emails },
        { name = "ALLOWED_DOMAIN", value = var.allowed_domain },
      ]
      secrets = [
        { name = "POSTGRES_URL", valueFrom = aws_secretsmanager_secret.postgres_url.arn },
        { name = "AUTH_SECRET", valueFrom = aws_secretsmanager_secret.auth_secret.arn },
        { name = "GOOGLE_CLIENT_SECRET", valueFrom = aws_secretsmanager_secret.google_client_secret.arn },
      ]
      logConfiguration = {
        logDriver = "awslogs"
        options = {
          "awslogs-group"         = aws_cloudwatch_log_group.watchmen.name
          "awslogs-region"        = var.aws_region
          "awslogs-stream-prefix" = "watchmen"
        }
      }
    }
  ])
}

resource "aws_ecs_service" "watchmen" {
  name            = "${var.app_name}-service"
  cluster         = aws_ecs_cluster.watchmen.id
  task_definition = aws_ecs_task_definition.watchmen.arn
  desired_count   = 1
  launch_type     = "FARGATE"

  network_configuration {
    subnets          = data.aws_subnets.default.ids
    security_groups  = [aws_security_group.ecs.id]
    assign_public_ip = true
  }

  load_balancer {
    target_group_arn = aws_lb_target_group.watchmen.arn
    container_name   = "watchmen"
    container_port   = 3000
  }

  depends_on = [aws_lb_listener.http]
}