image: atlassian/default-image:3

definitions:
  steps:
    - step: &security-scan
        name: Security Scan
        script:
          # Update and install dependencies
          - apt-get update && apt-get install -y git python3-pip curl unzip wget default-jdk

          # Install Python dependencies
          - pip3 install bandit safety selenium

          # Run Bandit
          - bandit -r . -f custom --msg-template "{abspath}:{line}:{severity}:{test_id}:{msg}" > bandit_results.txt

          # Run Safety
          - |
            if [ -f requirements.txt ]; then
              safety check -r requirements.txt > safety_results.txt
            else
              echo "No requirements.txt found. Skipping Safety check." > safety_results.txt
            fi

          # Install and run Gitleaks
          - curl -sL https://github.com/zricethezav/gitleaks/releases/download/v8.15.3/gitleaks_8.15.3_linux_x64.tar.gz | tar xz
          - ./gitleaks detect --source . -v > gitleaks_results.txt || echo "Gitleaks found potential secrets. Check gitleaks_results.txt for details." >> scan_results.txt

          # Install and run OWASP Dependency-Check
          - |
            DC_VERSION="7.4.4"
            curl -sL https://github.com/jeremylong/DependencyCheck/releases/download/v$DC_VERSION/dependency-check-$DC_VERSION-release.zip -o dc.zip
            unzip -q dc.zip && rm dc.zip
            ./dependency-check/bin/dependency-check.sh --scan . --format "HTML" --out dependency-check-report.html

          # Install and run OWASP ZAP
          # - |
          #   ZAP_VERSION="2.15.0"
          #   wget -q https://github.com/zaproxy/zaproxy/releases/download/v${ZAP_VERSION}/ZAP_${ZAP_VERSION}_Linux.tar.gz
          #   tar -xf ZAP_${ZAP_VERSION}_Linux.tar.gz && rm ZAP_${ZAP_VERSION}_Linux.tar.gz
          #   ZAP_${ZAP_VERSION}/zap.sh -cmd -quickurl $APPLICATION_URL -quickprogress -quickout zap-report.html || true

          # Run Selenium Chrome tests
          - |
            # Install ChromeDriver
            CHROME_DRIVER_VERSION=$(curl -sS https://chromedriver.storage.googleapis.com/LATEST_RELEASE)
            curl -sS -o /tmp/chromedriver.zip https://chromedriver.storage.googleapis.com/$CHROME_DRIVER_VERSION/chromedriver_linux64.zip
            unzip -o /tmp/chromedriver.zip -d /usr/local/bin/

            # Run Selenium tests from .side files
            echo "Running Selenium tests..." > selenium_results.txt
            if [ -d "tests/selenium" ]; then
              for side_file in tests/selenium/*.side; do
                if [ -f "$side_file" ]; then
                  echo "Running tests from $side_file" >> selenium_results.txt
                  python3 -m selenium.webdriver.chrome.service --executable-path=/usr/local/bin/chromedriver
                  if python3 -m selenium.webdriver.support.event_firing_webdriver --url $APPLICATION_URL --side-file "$side_file" >> selenium_results.txt 2>&1; then
                    echo "Tests in $side_file completed successfully" >> selenium_results.txt
                  else
                    echo "Tests in $side_file failed or encountered an error" >> selenium_results.txt
                  fi
                  echo "" >> selenium_results.txt
                fi
              done
            else
              echo "Directory tests/selenium not found. Skipping Selenium tests." >> selenium_results.txt
            fi

          # Combine all results
          - |
            {
              echo "Security Scan Results"
              echo "==================="
              echo "Bandit Results:"
              cat bandit_results.txt
              echo "Safety Results:"
              cat safety_results.txt
              echo "Gitleaks Results:"
              cat gitleaks_results.txt
              echo "ZAP Scan Summary:"
              if [ -f zap-report.html ]; then
                grep -A 5 "Alerts Summary" zap-report.html || echo "No alerts found in ZAP scan"
              else
                echo "ZAP scan did not produce a report"
              fi
              echo "Selenium Test Results:"
              cat selenium_results.txt
            } > scan_results.txt

          # Send results via email
          - |
            echo "Sending security scan results via email..."
            SUBJECT="Security Scan Results for $BITBUCKET_REPO_SLUG"
            BODY="Please find attached the security scan results for $BITBUCKET_REPO_SLUG (Build #$BITBUCKET_BUILD_NUMBER)."
            ATTACHMENT_CONTENT=$(base64 scan_results.txt)
            curl -X POST https://api.resend.com/emails \
              -H "Authorization: Bearer $RESEND_API_KEY" \
              -H "Content-Type: application/json" \
              -d '{
                "from": "Security Scanner <security-scanner@yourdomain.com>",
                "to": "'"$EMAIL_RECIPIENT"'",
                "subject": "'"$SUBJECT"'",
                "text": "'"$BODY"'",
                "attachments": [
                  {
                    "filename": "scan_results.txt",
                    "content": "'"$ATTACHMENT_CONTENT"'"
                  }
                ]
              }'

          # Post results to Slack
          - |
            curl -X POST -H 'Content-type: application/json' --data '{
              "text": "Security Scan Results for '"$BITBUCKET_REPO_SLUG"'",
              "attachments": [
                {
                  "color": "#36a64f",
                  "title": "Security Scan Completed",
                  "text": "'"$(cat scan_results.txt | sed 's/"/\\"/g')"'",
                  "footer": "Bitbucket Pipeline | '"$BITBUCKET_BUILD_NUMBER"'"
                }
              ]
            }' $SLACK_WEBHOOK_URL

        artifacts:
          - dependency-check-report.html
          - zap-report.html
          - selenium_results.txt
          - scan_results.txt

pipelines:
  default:
    - step: *security-scan

  branches:
    main:
      - step: *security-scan

  pull-requests:
    '**':
      - step: *security-scan

  custom:
    manual-security-scan:
      - step: *security-scan