SAST Static Analysis

Vibe Prompt

"Help me add SonarQube scanning in GitHub Actions to check for security vulnerabilities in JavaScript/TypeScript."

GitHub Actions + SonarQube

Below is a complete GitHub Actions workflow that triggers on pushes to main/develop and on pull requests targeting main. It checks out the code, runs the SonarQube scanner via the official action, and uploads the analysis results back to SonarCloud (or a self‑hosted SonarQube instance).

name: SAST Scan

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

jobs:
  sonar:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0  # Shallow clone is insufficient for SonarQube; full history needed

      - name: Set up JDK 21
        uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: 21

      - name: Cache SonarQube packages
        uses: actions/cache@v4
        with:
          path: ~/.sonar/cache
          key: ${{ runner.os }}-sonar
          restore-keys: |
            ${{ runner.os }}-sonar

      - name: Cache Maven packages
        uses: actions/cache@v4
        with:
          path: ~/.m2
          key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }}
          restore-keys: |
            ${{ runner.os }}-m2

      - name: SonarQube Scan
        uses: SonarSource/sonarcloud-github-action@master
        env:
          SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

What? This workflow runs the SonarQube scanner as part of the CI pipeline, analyzing source code for bugs, code smells, and security vulnerabilities.
Why? Early detection of issues reduces remediation cost dramatically—fixing a bug in production can be 100× more expensive than fixing it during development. SonarQube also provides a quality‑gate mechanism that can block merges if the scan fails.
How? The steps above are self‑explanatory: checkout the repo, install Java (required for the scanner), cache dependencies for speed, then invoke the SonarQube action. The SONAR_TOKEN secret must be configured in the repository settings to authenticate with your SonarQube instance.

CodeQL Scan

GitHub’s native static analysis tool, CodeQL, can be integrated in a separate job or the same workflow. The following snippet initializes CodeQL for JavaScript and Python, performs an auto‑build, and finally runs the analysis.

- name: Initialize CodeQL
  uses: github/codeql-action/init@v3
  with:
    languages: javascript, python

- name: Autobuild
  uses: github/codeql-action/autobuild@v3

- name: Perform CodeQL Analysis
  uses: github/codeql-action/analyze@v3
  with:
    category: "/language:javascript"

What? CodeQL constructs dataflow and control‑flow graphs from the source code and queries them to discover security patterns such as SQL injection, cross‑site scripting, and insecure deserialization.
Why? It is tightly integrated into GitHub, runs for free on public repositories, and provides actionable alerts directly in the code review UI. Using it alongside SonarQube gives you both broad code‑quality metrics and deep security‑specific queries.
How? The three steps above are the canonical pattern for a CodeQL workflow. If your project uses other languages (e.g., Go, Ruby), add them to the languages list. The autobuild step attempts to build the project using the default build commands; you can customize it with a commands block if needed.

SAST Tools Comparison

| Tool | Primary Language Support | Core Focus | Typical Integration | Pricing Model | |------|--------------------------|------------|--------------------|---------------| | SonarQube | 30+ languages (Java, JS/TS, Python, C/C++, PHP, etc.) | Code quality + security (SAST, AST, linting) | CI/CD pipelines (GitHub Actions, Jenkins, GitLab CI), IDE plugins | Community edition free; Enterprise paid | | CodeQL | 10+ languages (Java, JS/TS, Python, C/C++, Ruby, Go, etc.) | Deep security analysis (SAST) | GitHub Actions, GitHub Advanced Security (paid) | Free for public repos; paid for private repos | | Snyk Code | 10+ languages | Open‑source vulnerabilities + SAST | CI/CD, GitHub PR checks, IDE extensions | Limited free tier; paid plans for full coverage | | Semgrep | 20+ languages | Custom rule‑based scanning (SAST) | CLI, CI/CD (GitHub Actions, CircleCI), IDE | Community edition free; Pro paid | | Checkmarx | 20+ languages | Enterprise‑grade SAST with AST | CI/CD, IDE, SaaS | Commercial licensing |

What? Each tool varies in language coverage, detection depth, and integration options.
Why? Choosing the right tool depends on your tech stack, budget, and compliance requirements. For example, if you already use GitHub, CodeQL is a zero‑setup option for public repos, while SonarQube offers more extensive code‑quality metrics for large teams.
How? Evaluate your project’s most critical languages, then test the tool’s CLI locally before embedding it into your CI pipeline.

Vibe Prompt for Semgrep Rule

"Write a Semgrep rule that detects SQL Injection in Python code."

rules:
  - id: sql-injection-detection
    patterns:
      - pattern: |
          $CURSOR.execute("..." + $USER_INPUT + "...")
      - pattern: |
          f"SELECT ... WHERE id = {$USER_INPUT}"
    message: "Potential SQL Injection detected"
    languages: [python]
    severity: ERROR

What? This Semgrep rule flags common patterns where user input is directly concatenated into SQL queries.
Why? SQL Injection remains one of the top OWASP vulnerabilities; automated detection in the CI pipeline ensures developers catch it before code reaches production.
How? Add the rule to a .yaml file (e.g., semgrep.yml), then invoke Semgrep in your CI job:

- name: Run Semgrep
  uses: returntocorp/semgrep-action@v1
  with:
    config: >-
      path/to/semgrep.yml

Key Takeaways

SAST Tools Comparison Table (Expanded)

| Tool | Language Support | Integration Options | Cost | Typical Use‑Case | |------|------------------|---------------------|------|-----------------| | SonarQube | 30+ languages, strong support for Java, C/C++, Python, JavaScript, TypeScript, etc. | CI/CD (GitHub Actions, Jenkins, GitLab), IDE plugins (IntelliJ, Eclipse), REST API | Free Community Edition; paid Enterprise | Large enterprises needing comprehensive code quality + security dashboards | | CodeQL | 10+ languages, excellent for Java, JS/TS, Python, C/C++, Ruby, Go | GitHub Actions, GitHub Advanced Security (GHAS), CLI | Free for public repos; paid for private | Teams already on GitHub that want native security scanning with minimal configuration | | Snyk Code | 10+ languages, focuses on OWASP Top 10 | CI/CD, GitHub PR checks, IDE (VS Code, IntelliJ) | Free tier limited; paid plans for full features | Developers who want quick setup and integration with Snyk’s vulnerability database | | Semgrep | 20+ languages, supports custom rules | CLI, CI/CD (GitHub Actions, CircleCI, Travis CI), IDE (Emacs, Vim) | Free Community Edition; paid Pro | Security teams that need to write domain‑specific rules (e.g., banking, healthcare) | | Checkmarx | 20+ languages, includes AST and flow‑analysis | CI/CD, IDE, SaaS portal | Commercial licensing | Enterprises requiring high‑assurance scanning with detailed reporting and compliance features |

GitHub Actions Integration (Step‑by‑Step)

  1. Create a new file .github/workflows/sast-scan.yml in your repository.
  2. Define the trigger (push to main/develop, pull_request to main) as shown above.
  3. Checkout the repository with full history (fetch-depth: 0) because SonarQube needs the git history for blame information.
  4. Install required tools – Java for SonarQube, Node.js if you run additional linting steps.
  5. Cache dependencies to speed up subsequent runs.
  6. Run the SonarQube action – this will invoke the SonarScanner, analyze the code, and post a comment on the PR with the results.
  7. Optional: Add a CodeQL job in the same workflow or a separate one to cover additional languages.

What? This workflow automates security and quality checks at every commit.
Why? It enforces a "security‑by‑default" culture, reduces manual review time, and provides measurable metrics for the development team.
How? Follow the steps above; customize the SONAR_TOKEN secret and the languages list in CodeQL as needed.

Blocking Pull Requests with Quality Gates

SonarQube’s Quality Gate is a set of conditions (e.g., no new bugs, no critical vulnerabilities, test coverage ≥ 80%). You can configure it in the SonarQube UI:

  • Navigate to Quality Profiles → Quality Gates.
  • Create a new gate or edit the default one.
  • Add conditions such as New Bugs = NONE, New Security Hotspots = NONE, Coverage = >= 80%.

Then, in the GitHub Action, add a step that calls the sonarqube/check action (or use the sonarcloud/github-action with args: "-d.qualitygate.wait=true"). If the quality gate fails, the PR comment will indicate the failure and the CI job will fail, effectively blocking merge.

What? Quality gates provide an automated checkpoint that prevents low‑quality or insecure code from entering the main branch.
Why? They enforce consistent standards across the team and protect the product from regressions.
How? Configure the gates in SonarQube, enable the wait flag in the action, and monitor the PR comments for pass/fail status.

SAST: Catching Bugs Early in the Development Lifecycle

What Is SAST?

Static Application Security Testing (SAST) analyzes source code without executing it. It parses the abstract syntax tree (AST) or uses pattern matching to locate potential security weaknesses, coding standards violations, and maintainability issues.

What Can SAST Detect?

| Vulnerability | Example Code | SonarQube Rule Key | |---------------|--------------|--------------------| | SQL Injection | query = "SELECT * FROM users WHERE id = " + userInput | sqli | | Cross‑Site Scripting (XSS) | element.innerHTML = userProvidedString | xss | | Hard‑Coded Credentials | password = "admin123" | hardcoded | | Buffer Overflow | char buf[10]; strcpy(buf, input); | buffer_overflow | | Unvalidated Redirect | redirectUrl = request.getParameter("url"); response.sendRedirect(redirectUrl); | redirect | | Command Injection | Runtime.getRuntime().exec("rm " + userInput) | command_injection | | Insecure Deserialization | ObjectInputStream ois = new ObjectInputStream(stream); obj = ois.readObject(); | deserialization |

Why? Detecting these issues early prevents costly remediation later (e.g., a data breach caused by SQL injection can cost millions). SonarQube’s rule engine can be tuned to match your organization’s risk tolerance.

How? Enable the relevant rules in your SonarQube project, run the scanner, and review the findings in the SonarQube UI. You can also use the SonarQube API to automatically assign issues to team members.

Pros and Cons of SAST

| Advantages | Disadvantages | |------------|----------------| | Early detection – bugs are cheaper to fix when caught during coding. | False positives – static analysis can flag benign code (e.g., safe string concatenation). | | No runtime environment needed – scans are fast and repeatable. | Limited runtime insight – cannot detect logic flaws that only appear when the app runs. | | Direct line numbers – developers see exactly which line needs fixing. | Less effective for dynamic languages – Python/JS analysis may miss subtle runtime issues. | | CI/CD integration – can be part of automated pipelines. | Rule maintenance – new vulnerabilities require updated rule sets. |

Why? Understanding the trade‑offs helps you design a balanced security strategy that combines SAST with dynamic (DAST) and runtime (RASP) testing.
How? Use SAST for “first line of defense,” then complement it with SAST’s findings in a broader testing pipeline.

Best Practices for SAST in a Development Workflow

  1. Make SAST a required gate in CI/CD – no merge into main unless the scan passes.
  2. Configure rules to match your risk profile – disable noisy rules that are not relevant (e.g., false positives for third‑party libraries).
  3. Use incremental analysis – only re‑scan changed files to reduce runtime.
  4. Integrate with issue trackers – automatically create tickets in Jira/Linear for each new security finding.
  5. Educate developers – provide quick fixes and explanations for common patterns (e.g., using parameterized queries).
  6. Periodically review rule effectiveness – adjust thresholds based on team feedback and actual vulnerability data.

What? These practices ensure SAST delivers actionable insights without overwhelming developers.
Why? They maximize the return on investment: fewer false positives, faster

Member Exclusive Free Tutorial

This chapter is free exclusive content for registered members! Please login or register to unlock immediately.

Login / Register Now