For AI agents: the complete documentation index is available at https://nhanbe.id.vn/llms.txt, the full documentation bundle is available at https://nhanbe.id.vn/llms-full.txt, and this page is available as Markdown at https://nhanbe.id.vn/others/tools/codeql-note.md.

Guide to installing and running the latest CodeQL CLI on Windows for AEM multi-module projects.

CodeQL for AEM Projects

Introduction to CodeQL

CodeQL is GitHub's industry-leading semantic code analysis engine. It treats source code like relational data: your codebase is extracted into a specialized database (CodeQL Database), allowing you to execute expressive queries written in QL (an object-oriented query language) to detect security vulnerabilities, dangerous data flows, and code smells before code merges into production.

Key Advantages for Local AEM Development

  • Inter-Procedural Taint Tracking: Tracks untrusted input across multiple functions, classes, and service layers (e.g., from an HTTP request parameter in a Sling Servlet down to a JCR session or query execution).
  • Multi-Language Support in AEM: Seamlessly scans both the OSGi Java backend (core) and the client-side JavaScript/TypeScript frontend (ui.frontend).
  • Standardized Diagnostic Reports: Generates standard SARIF (Static Analysis Results Interchange Format) or CSV outputs that can be inspected directly inside VS Code or integrated into CI/CD pipelines.

1. Installing CodeQL CLI on Windows

The CodeQL Bundle includes the CLI binary, all standard query packs for supported languages, and an embedded Java Runtime Environment (JRE) for running the query engine.

[JDK Requirement for AEM Java Extraction]

While the CodeQL Bundle includes its own embedded JRE to run the CLI engine, extracting a Java database requires a locally installed JDK compatible with your AEM version (e.g., JDK 11 for AEM 6.5 or JDK 17/21 for AEM as a Cloud Service) configured in your PATH or JAVA_HOME.

1.1 Automatic Setup Script (PowerShell)

Run this PowerShell script to automatically download the latest CodeQL bundle and configure your environment:

PowerShell (Run as Administrator or User)
# 1. Get the latest CodeQL bundle version from GitHub API
$LatestRelease = Invoke-RestMethod -Uri "https://api.github.com/repos/github/codeql-action/releases/latest"
$Tag = $LatestRelease.tag_name
$CodeQLVersion = $Tag -replace 'codeql-bundle-v', ''

# 2. Download the Windows bundle
$ArchiveName = "codeql-bundle-win64.tar.gz"
$DownloadUrl = "https://github.com/github/codeql-action/releases/download/$Tag/$ArchiveName"
$ArchivePath = Join-Path $env:TEMP $ArchiveName
$InstallRoot = Join-Path $env:LOCALAPPDATA "CodeQL"

Write-Host "Downloading CodeQL $CodeQLVersion..."
Invoke-WebRequest -Uri $DownloadUrl -OutFile $ArchivePath

# 3. Extract the bundle
Write-Host "Extracting to $InstallRoot..."
New-Item -ItemType Directory -Path $InstallRoot -Force | Out-Null
tar -xzf $ArchivePath -C $InstallRoot

# 4. Add to PATH
$CodeQLBin = Join-Path $InstallRoot "codeql"
$UserPath = [Environment]::GetEnvironmentVariable("Path", "User")
$UserEntries = @($UserPath -split ";" | Where-Object { $_ })
if ($UserEntries -notcontains $CodeQLBin) {
  [Environment]::SetEnvironmentVariable("Path", (($UserEntries + $CodeQLBin) -join ";"), "User")
  Write-Host "Added $CodeQLBin to User PATH"
}
$env:Path = "$CodeQLBin;$env:Path"

# 5. Clean up
Remove-Item $ArchivePath -Force

# 6. Verify installation
Write-Host "`nVerifying installation..."
codeql --version
codeql resolve languages
codeql resolve packs

1.2 Verifying the Installation

Close and reopen your terminal, then run:

PowerShell
# Check CLI version
codeql --version

# Verify supported languages (ensure java and javascript are listed)
codeql resolve languages

# Verify bundled query packs
codeql resolve packs

Expected output should show java and javascript in the supported languages list, and query packs like codeql/java-queries and codeql/javascript-queries in the packs list.


2. Core Concepts

Understanding CodeQL terminology helps configure appropriate analysis targets for AEM projects:

ConceptRole & Description
DatabaseRelational snapshot of the extracted source code AST, symbol tables, and control-flow graphs (one database per language).
ExtractorThe language-specific module that builds the database (e.g., hooks into javac for Java, or parses source trees for JS/TS).
Query Suite (.qls)A curated collection of queries grouped for specific audit objectives.
SARIF / CSVStructured result export formats. SARIF is the OASIS open standard used by GitHub and IDE viewers.

Commonly Used Query Suites

  • code-scanning: The default suite used in GitHub Code Scanning. Highly tuned for high precision with low false-positive rates.
  • security-extended: Extends standard scanning to cover additional common vulnerabilities and lower-severity security risks.
  • security-and-quality: The most comprehensive suite. Includes all security rules plus code maintainability, dead code detection, and code smells.

3. Creating CodeQL Databases for AEM

A typical AEM Maven Archetype project contains multiple modules with distinct languages:

AEM Project Structure
my-aem-project/
├── pom.xml                     ← Reactor parent POM
├── core/                       ← Java OSGi Services & Sling Models
├── ui.apps/                    ← JCR Components & Clientlibs
├── ui.content/                 ← Sample Content & Configurations
├── ui.frontend/                ← JS / TS / Webpack / Vue / React
└── all/                        ← Container package

3.1 Creating the Java Database (Maven Integration)

Because Java is a compiled language, CodeQL's extractor must observe javac compiler invocations during an active build. Pass the Maven compilation command via --command:

PowerShell
codeql database create db-java --language=java --source-root=. --command="mvn clean install -DskipTests -B -ntp" --overwrite
[Critical: Always Include the Clean Goal]

Always specify clean in mvn clean install. If Maven skips compilation due to existing build artifacts (incremental build), CodeQL will not intercept any javac executions and will fail with the error:
"No source code seen during build".

3.2 Creating the Frontend JS/TS Database (ui.frontend)

The JavaScript/TypeScript extractor does not require a build step; it crawls and indexes files directly from the specified directory:

PowerShell
codeql database create db-js --language=javascript --source-root="ui.frontend" --overwrite

4. Running Local Analysis & Exporting Results

Once the database has been constructed, run queries against it using codeql database analyze.

4.1 Running the Security and Quality Suite (SARIF Format)

Analyze Java (SARIF)
codeql database analyze db-java --format=sarif-latest --output=results-java.sarif --threads=0 codeql/java-queries:codeql-suites/java-security-and-quality.qls
Analyze Frontend (SARIF)
codeql database analyze db-js --format=sarif-latest --output=results-js.sarif --threads=0 codeql/javascript-queries:codeql-suites/javascript-security-and-quality.qls

4.2 Exporting Results to CSV (Spreadsheet Review)

If you need to review issues in Excel or Google Sheets, export using --format=csv:

Export Java Findings to CSV
codeql database analyze db-java --format=csv --output=results-java.csv --threads=0 codeql/java-queries:codeql-suites/java-security-and-quality.qls
Export Frontend Findings to CSV
codeql database analyze db-js --format=csv --output=results-js.csv --threads=0 codeql/javascript-queries:codeql-suites/javascript-security-and-quality.qls

5. Reviewing Findings in Visual Studio Code

Inspecting raw SARIF files in text editors is difficult due to verbose JSON formatting. Using dedicated VS Code extensions enables an interactive security dashboard:

  1. Install the Extension: Install SARIF Viewer (by Microsoft DevLabs) or the official CodeQL extension from the VS Code Marketplace.
  2. Load Results: Press Ctrl + Shift + P, run SARIF: Open SARIF Log, and pick results-java.sarif or results-js.sarif.
  3. Trace Taint Paths: Clicking on any finding in the SARIF Viewer panel will navigate directly to the affected source code file, highlighting the tainted data-flow path step-by-step from source to sink.
[Interactive Query Writing]

With the CodeQL for Visual Studio Code extension installed, you can add db-java to the database view, author custom .ql queries, and execute them on-the-fly with full syntax highlighting, AST inspection, and auto-complete.


6. Performance Tips & Best Practices

  • Maximize Concurrency with --threads=0: Passes all available CPU cores to the query evaluator and extractor. For systems with limited RAM, specify an explicit thread count (e.g., --threads=4) to avoid resource exhaustion.
  • Allocate Sufficient Heap Memory: For large AEM multi-module projects, provide explicit memory limit via --ram (e.g., --ram=8192 for 8GB) to accelerate QL query compilation and graph evaluation.
  • Exclude Generated Databases from Version Control: Always add CodeQL output directories and database folders to your .gitignore:
.gitignore
# CodeQL Databases and Analysis Results
db-java/
db-js/
*.sarif
*.csv
.codeql/
  • Speed Up Maven Database Creation: Use -DskipTests -B -ntp during codeql database create to omit test compilation and eliminate verbose download progress logs, reducing creation time by up to 70%.

References