name: Security Scan

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main, develop]

jobs:
  security:
    name: Security Analysis
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup Go
        uses: actions/setup-go@v5
        with:
          go-version: '1.25'

      - name: Run govulncheck
        uses: golang/govulncheck-action@v1
        with:
          go-version-input: '1.25'
          go-package: ./...

      - name: Run gosec
        uses: securego/gosec@master
        with:
          args: '-fmt sarif -out gosec-results.sarif ./...'

      - name: Upload gosec results
        uses: actions/upload-artifact@v4
        if: always()
        with:
          name: gosec-results
          path: gosec-results.sarif

      - name: Check for unsafe package usage
        run: |
          if grep -r "unsafe\." --include="*.go" ./internal ./cmd ./pkg 2>/dev/null; then
            echo "ERROR: unsafe package usage detected"
            exit 1
          fi
          echo "No unsafe package usage found"

      - name: Verify dependencies
        run: |
          go mod verify
          echo "Go modules verified"

  native-security:
    name: Native Library Security
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Install dependencies
        run: |
          sudo apt-get update
          sudo apt-get install -y cmake build-essential

      - name: Build with AddressSanitizer
        run: |
          cd native
          mkdir -p build
          cd build
          cmake .. -DCMAKE_BUILD_TYPE=Debug -DENABLE_ASAN=ON
          make -j$(nproc)

      - name: Run tests with ASan
        run: |
          cd native/build
          ASAN_OPTIONS=detect_leaks=1 ctest --output-on-failure

      - name: Build with UndefinedBehaviorSanitizer
        run: |
          cd native
          rm -rf build
          mkdir -p build
          cd build
          cmake .. -DCMAKE_BUILD_TYPE=Debug -DCMAKE_C_FLAGS="-fsanitize=undefined" -DCMAKE_CXX_FLAGS="-fsanitize=undefined"
          make -j$(nproc)

      - name: Run tests with UBSan
        run: |
          cd native/build
          ctest --output-on-failure
