name: VibeShield Phase 1 CI/CD

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
            ./

      # 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@0.33.1
        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. Automated Scanner Tests
      - name: Run VibeShield scanner tests
        run: |
          npx jest \
            --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@0.33.1
        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}"
