name: VibeShield Phase 1 CI/CD
#added comment
#remove comment

on:
  push:
    branches: [main]
  pull_request:
  workflow_dispatch:

permissions:
  contents: read

concurrency:
  group: ci-${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  security:
    name: Security and Automated Tests
    runs-on: ubuntu-latest
    timeout-minutes: 25

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: "22"
          cache: npm

      # 1. Dependency and Supply-Chain Checks
      - name: Install dependencies
        run: |
          test -f package.json
          test -f package-lock.json
          npm ci

      - name: Audit npm dependencies
        run: npm audit --audit-level=high

      - name: Scan dependencies with OSV-Scanner
        uses: google/osv-scanner-action/osv-scanner-action@v2.2.2
        with:
          scan-args: |-
            --recursive
            --config=./osv-scanner.toml
            ./

      # 2. Secret Scanning
      - name: Scan for exposed secrets
        uses: gitleaks/gitleaks-action@v3
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      # 3. Source and Configuration Scanning
      - name: Scan source with Trivy
        uses: aquasecurity/trivy-action@v0.36.0
        with:
          scan-type: fs
          scan-ref: .
          scanners: vuln,misconfig,secret
          severity: HIGH,CRITICAL
          ignore-unfixed: true
          exit-code: "1"
          format: table

      - name: Validate VibeShield configuration
        run: |
          node --input-type=module <<'EOF'
          import fs from "node:fs";

          const files = [
            "test/config.json",
            "test/get.json",
            "test/post.json",
            "test/put.json",
            "test/delete.json"
          ];

          for (const file of files) {
            if (!fs.existsSync(file)) {
              throw new Error(`Missing required file: ${file}`);
            }

            JSON.parse(fs.readFileSync(file, "utf8"));
            console.log(`Valid JSON: ${file}`);
          }

          const config = JSON.parse(
            fs.readFileSync("test/config.json", "utf8")
          );

          if (!Number.isFinite(config.timeoutMs) || config.timeoutMs <= 0) {
            throw new Error("timeoutMs must be positive.");
          }

          const target = new URL(config.targetUrl);

          if (!["http:", "https:"].includes(target.protocol)) {
            throw new Error("targetUrl must use HTTP or HTTPS.");
          }

          for (const method of ["GET", "POST", "PUT", "DELETE"]) {
            const file = `test/${method.toLowerCase()}.json`;
            const cfg = JSON.parse(fs.readFileSync(file, "utf8"));

            if (cfg.method !== method) {
              throw new Error(`${file}: expected method ${method}`);
            }

            if (!Array.isArray(cfg.endpoints)) {
              throw new Error(`${file}: endpoints must be an array`);
            }

            for (const endpoint of cfg.endpoints) {
              if (
                typeof endpoint.path !== "string" ||
                !endpoint.path.startsWith("/") ||
                endpoint.path.startsWith("//")
              ) {
                throw new Error(`${file}: invalid endpoint path`);
              }

              const url = new URL(endpoint.path, target);

              if (url.origin !== target.origin) {
                throw new Error(`${file}: endpoint escapes target origin`);
              }
            }
          }

          if (config.security?.allowDestructiveTests === true) {
            throw new Error(
              "Destructive scanner tests must be disabled in CI."
            );
          }

          console.log("VibeShield configuration validation passed.");
          EOF

      # 4. Code Integrity Checks
      - name: Check whitespace and merge conflicts
        run: |
          git diff --check

          if git grep -n -E '^(<<<<<<< |=======|>>>>>>> )' -- \
            '*.js' '*.json' '*.yml' '*.yaml' '*.groovy' Jenkinsfile; then
            echo "Merge conflict markers detected."
            exit 1
          fi

        # 5. Start API and Run Automated Scanner Tests
      - name: Start API server
        run: |
          nohup node server.js > server.log 2>&1 &
          echo $! > server.pid

      - name: Wait for API server
        run: |
          for i in {1..30}; do
            if curl --fail --silent http://127.0.0.1:3000/health; then
              echo "API server is ready."
              exit 0
            fi

            sleep 2
          done

          echo "API server failed to start."
          cat server.log
          exit 1

      # 5. Automated Scanner Tests
      - name: Run VibeShield scanner tests
        run: |
          node --experimental-vm-modules ./node_modules/jest/bin/jest.js \
            --config='{"testEnvironment":"node","testMatch":["<rootDir>/test/scanner/**/*.test.js"]}' \
            --runInBand

      # 6. Application Build
      - name: Build application
        run: npm run build

  docker:
    name: Build, Scan and Publish Docker Image
    needs: security
    runs-on: ubuntu-latest
    timeout-minutes: 25

    permissions:
      contents: read
      packages: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      # 7. Build Docker Image
      - name: Build application image
        run: |
          docker build \
            --pull \
            --file test/scanner/DockerFile \
            --tag vibeshield-app:${{ github.sha }} \
            .

      # 8. Scan Docker Image
      - name: Scan Docker image with Trivy
        uses: aquasecurity/trivy-action@v0.36.0
        with:
          image-ref: vibeshield-app:${{ github.sha }}
          scan-type: image
          scanners: vuln,misconfig,secret
          severity: HIGH,CRITICAL
          ignore-unfixed: true
          exit-code: "1"
          format: table

      # 9. Push Only Verified Images to GitHub Container Registry
      - name: Log in to GitHub Container Registry
        if: github.event_name == 'push' && github.ref == 'refs/heads/main'
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Push verified image
        if: github.event_name == 'push' && github.ref == 'refs/heads/main'
        env:
          IMAGE_NAME: ghcr.io/${{ github.repository }}
          IMAGE_TAG: ${{ github.sha }}
        run: |
          IMAGE_NAME=$(echo "$IMAGE_NAME" | tr '[:upper:]' '[:lower:]')

          docker tag \
            "vibeshield-app:${IMAGE_TAG}" \
            "${IMAGE_NAME}:${IMAGE_TAG}"

          docker push "${IMAGE_NAME}:${IMAGE_TAG}"

          echo "Published image: ${IMAGE_NAME}:${IMAGE_TAG}"

  deploy:
    name: Deploy to AWS EKS
    needs: docker
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'

    runs-on: ubuntu-latest
    timeout-minutes: 20

    permissions:
      contents: read
      id-token: write

    env:
      AWS_REGION: ${{ vars.AWS_REGION }}
      EKS_CLUSTER_NAME: ${{ vars.EKS_CLUSTER_NAME }}
      IMAGE_NAME: ghcr.io/${{ github.repository }}
      IMAGE_TAG: ${{ github.sha }}

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Normalize GHCR image name
        shell: bash
        run: |
          IMAGE_NAME="$(echo "$IMAGE_NAME" | tr '[:upper:]' '[:lower:]')"
          echo "IMAGE_NAME=$IMAGE_NAME" >> "$GITHUB_ENV"

      - name: Debug OIDC token claims
        uses: actions/github-script@v7
        with:
          script: |
            const token = await core.getIDToken('sts.amazonaws.com');

            const payload = JSON.parse(
              Buffer.from(token.split('.')[1], 'base64url').toString()
            );

            core.info(JSON.stringify({
              iss: payload.iss,
              aud: payload.aud,
              sub: payload.sub,
              repository: payload.repository,
              ref: payload.ref
            }, null, 2));
      #mens
      - name: Authenticate to AWS using OIDC
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
          aws-region: ${{ vars.AWS_REGION }}

      - name: Verify AWS identity
        run: aws sts get-caller-identity

      - name: Connect to EKS cluster
        run: |
          aws eks update-kubeconfig \
            --region "$AWS_REGION" \
            --name "$EKS_CLUSTER_NAME"

      - name: Verify EKS connectivity
        run: |
          kubectl get nodes
          kubectl cluster-info

      - name: Render and apply Kubernetes Deployment
        shell: bash
        run: |
          set -euo pipefail

          echo "Deploying image: ${IMAGE_NAME}:${IMAGE_TAG}"

          envsubst < test/scanner/k8s/deployment.yaml > /tmp/vibeshield-deployment.yaml

          # Fail safely if the image variables were not substituted.
          if grep -Eq '\$\{(IMAGE_NAME|IMAGE_TAG)\}' /tmp/vibeshield-deployment.yaml; then
            echo "Image variables were not substituted in the Kubernetes manifest."
            exit 1
          fi

          kubectl apply -f /tmp/vibeshield-deployment.yaml

      - name: Apply Kubernetes Service
        run: |
          kubectl apply -f test/scanner/k8s/service.yaml

      - name: Wait for rollout
        run: |
          kubectl rollout status deployment/vibeshield \
            --timeout=300s

      - name: Display deployment status
        run: |
          echo "=== Deployment ==="
          kubectl get deployment vibeshield

          echo "=== Pods ==="
          kubectl get pods -l app=vibeshield -o wide

          echo "=== Service ==="
          kubectl get service vibeshield-service

      - name: Display load balancer hostname
        shell: bash
        run: |
          for i in {1..30}; do
            HOSTNAME="$(kubectl get service vibeshield-service \
              -o jsonpath='{.status.loadBalancer.ingress[0].hostname}')"

            if [ -n "$HOSTNAME" ]; then
              echo "Load balancer hostname: $HOSTNAME"
              echo "Application URL: http://$HOSTNAME"
              exit 0
            fi

            echo "Waiting for AWS load balancer provisioning..."
            sleep 10
          done

          echo "Load balancer hostname is not available yet."
          kubectl describe service vibeshield-service
          exit 1

  monitoring:
    name: Install Prometheus Monitoring on EKS
    needs: deploy
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'

    runs-on: ubuntu-latest
    timeout-minutes: 25

    permissions:
      contents: read
      id-token: write

    env:
      AWS_REGION: ${{ vars.AWS_REGION }}
      EKS_CLUSTER_NAME: ${{ vars.EKS_CLUSTER_NAME }}

    steps:
      # 1. Authenticate with AWS
      - name: Authenticate to AWS using OIDC
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
          aws-region: ${{ vars.AWS_REGION }}

      # 2. Connect to EKS
      - name: Connect to EKS cluster
        run: |
          aws eks update-kubeconfig \
            --region "$AWS_REGION" \
            --name "$EKS_CLUSTER_NAME"

          kubectl get nodes

      # 3. Install Helm
      - name: Set up Helm
        uses: azure/setup-helm@v4

      # 4. Add Prometheus Helm repository
      - name: Add Prometheus Helm repository
        run: |
          helm repo add prometheus-community \
            https://prometheus-community.github.io/helm-charts

          helm repo update

      # 5. Install Prometheus Monitoring Stack
      - name: Deploy Prometheus Monitoring Stack
        run: |
          helm upgrade --install vibeshield-monitoring \
            prometheus-community/kube-prometheus-stack \
            --namespace monitoring \
            --create-namespace \
            --set grafana.enabled=false \
            --set alertmanager.enabled=false \
            --set prometheus-node-exporter.enabled=true \
            --set kube-state-metrics.enabled=true \
            --set prometheus.prometheusSpec.retention=7d \
            --wait \
            --timeout 15m

      # 6. Verify Prometheus
      - name: Verify Prometheus Monitoring
        run: |
          echo "=== Monitoring Pods ==="
          kubectl get pods -n monitoring

          echo "=== Monitoring Services ==="
          kubectl get svc -n monitoring

          echo "=== Node Exporter ==="
          kubectl get daemonsets -n monitoring

          echo "=== Kube State Metrics ==="
          kubectl get deployments -n monitoring

          echo "=== Prometheus Status ==="
          kubectl get prometheus -n monitoring
