Skip to content

Conversation

@Sazwanismail
Copy link
Owner

@Sazwanismail Sazwanismail commented Nov 11, 2025

User description

CodeQL Advanced Implementation

πŸš€ Complete Advanced CodeQL Setup

1. Advanced CodeQL Configuration Structure

.github/
β”œβ”€β”€ workflows/
β”‚   β”œβ”€β”€ codeql-advanced.yml
β”‚   β”œβ”€β”€ codeql-security-gates.yml
β”‚   └── codeql-custom-analysis.yml
β”œβ”€β”€ codeql/
β”‚   β”œβ”€β”€ config/
β”‚   β”‚   β”œβ”€β”€ codeql-config.yml
β”‚   β”‚   β”œβ”€β”€ query-suites.qls
β”‚   β”‚   └── performance-config.yml
β”‚   β”œβ”€β”€ custom-queries/
β”‚   β”‚   β”œβ”€β”€ qlpack.yml
β”‚   β”‚   β”œβ”€β”€ Security/
β”‚   β”‚   β”œβ”€β”€ Performance/
β”‚   β”‚   └── Architecture/
β”‚   └── scripts/
β”‚       β”œβ”€β”€ aggregate-results.py
β”‚       └── security-gates.py

2. Main Advanced CodeQL Workflow

# .github/workflows/codeql-advanced.yml
name: "Advanced CodeQL Analysis"

on:
  push:
    branches: [ main, develop, release/* ]
    paths:
      - 'src/**'
      - 'lib/**'
      - '**.java'
      - '**.js'
      - '**.ts'
      - '**.py'
      - '**.go'
      - '**.cpp'
    paths-ignore:
      - '**/*.md'
      - '**/*.txt'
      - '**/test/**'
      - '**/spec/**'
  pull_request:
    branches: [ main, develop ]
  schedule:
    - cron: '0 2 * * 1'  # Weekly on Monday at 2 AM UTC
  workflow_dispatch:
    inputs:
      analysis-depth:
        description: 'Analysis depth level'
        required: true
        default: 'deep'
        type: choice
        options:
        - quick
        - standard
        - deep
      include-experimental:
        description: 'Include experimental queries'
        required: false
        type: boolean
        default: false

env:
  CODEQL_ACTION_VERBOSITY: info
  CODEQL_POWERFUL_ANALYSIS: true
  CODEQL_EXTRACTOR_JAVA_AGENT_DISABLE_KOTLIN: false

jobs:
  initialize:
    name: Initialize Analysis
    runs-on: ubuntu-latest
    outputs:
      matrix: ${{ steps.set-matrix.outputs.matrix }}
      database-locations: ${{ steps.set-matrix.outputs.database-locations }}
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Set up analysis matrix
        id: set-matrix
        run: |
          MATRIX_JSON=$(python .github/codeql/scripts/detect-languages.py)
          echo "matrix=$MATRIX_JSON" >> $GITHUB_OUTPUT
          echo "database-locations=$(echo $MATRIX_JSON | jq -r '.include[].database_location' | tr '\n' ',' | sed 's/,$//')" >> $GITHUB_OUTPUT

  analyze-multi-language:
    name: Analyze (${{ matrix.language }})
    needs: initialize
    runs-on: ${{ matrix.runner }}
    strategy:
      fail-fast: false
      matrix: ${{ fromJSON(needs.initialize.outputs.matrix) }}

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Initialize CodeQL
        uses: github/codeql-action/init@v3
        with:
          languages: ${{ matrix.language }}
          queries: ${{ matrix.queries }}
          config-file: ./.github/codeql/config/codeql-config.yml
          config: ${{ matrix.config }}
          tools: latest
          database: ${{ matrix.database_location }}

      - name: Build ${{ matrix.language }} code
        if: matrix.build-command
        run: ${{ matrix.build-command }}

      - name: Perform CodeQL Analysis
        uses: github/codeql-action/analyze@v3
        with:
          category: "/language:${{ matrix.language }}"
          output: sarif-results/${{ matrix.language }}
          upload-database: true
          skip-queries: ${{ github.event_name == 'schedule' && 'security' || '' }}
          threads: ${{ matrix.threads }}
          ram: ${{ matrix.ram }}
        env:
          CODEQL_RAM: ${{ matrix.ram }}
          CODEQL_THREADS: ${{ matrix.threads }}

  custom-query-analysis:
    name: Custom Query Analysis
    needs: analyze-multi-language
    runs-on: ubuntu-latest
    if: always()

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Download CodeQL databases
        run: |
          mkdir -p databases
          echo "${{ needs.initialize.outputs.database-locations }}" | tr ',' '\n' | xargs -I {} cp -r {} databases/

      - name: Run Custom Queries
        uses: github/codeql-action/analyze@v3
        with:
          queries: ./.github/codeql/custom-queries/
          packs: ./.github/codeql/custom-queries/
          output: sarif-results/custom
          category: "custom"

  security-metrics:
    name: Generate Security Metrics
    needs: [analyze-multi-language, custom-query-analysis]
    runs-on: ubuntu-latest
    if: always()

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Generate Security Report
        run: |
          python .github/codeql/scripts/aggregate-results.py

      - name: Upload Security Metrics
        uses: actions/upload-artifact@v4
        with:
          name: security-metrics
          path: |
            security-report.html
            codeql-metrics.json
          retention-days: 30

      - name: Update Security Dashboard
        run: |
          echo "## CodeQL Security Analysis Complete" >> $GITHUB_STEP_SUMMARY
          echo "βœ… Multi-language analysis completed" >> $GITHUB_STEP_SUMMARY
          echo "πŸ“Š Custom queries executed" >> $GITHUB_STEP_SUMMARY
          echo "πŸ“ˆ Security metrics generated" >> $GITHUB_STEP_SUMMARY

3. Language Detection Script

# .github/codeql/scripts/detect-languages.py
#!/usr/bin/env python3
import json
import os
from pathlib import Path

def detect_languages():
    """Detect programming languages in the repository"""
    language_files = {
        'java': ['**/*.java', '**/pom.xml', '**/build.gradle', '**/build.gradle.kts'],
        'javascript': ['**/*.js', '**/*.ts', '**/package.json', '**/yarn.lock'],
        'python': ['**/*.py', '**/requirements.txt', '**/Pipfile', '**/pyproject.toml'],
        'go': ['**/*.go', '**/go.mod'],
        'cpp': ['**/*.cpp', '**/*.hpp', '**/*.c', '**/*.h', '**/CMakeLists.txt'],
    }
    
    detected_languages = []
    
    for lang, patterns in language_files.items():
        for pattern in patterns:
            if list(Path('.').glob(pattern)):
                detected_languages.append(lang)
                break
    
    # Default to javascript if no languages detected
    if not detected_languages:
        detected_languages = ['javascript']
    
    return detected_languages

def generate_matrix(languages):
    """Generate workflow matrix configuration"""
    matrix_config = {
        'include': []
    }
    
    language_configs = {
        'java': {
            'runner': 'ubuntu-latest',
            'queries': 'security-and-quality,security-extended',
            'build-command': './gradlew build -x test || mvn compile -DskipTests',
            'threads': 4,
            'ram': 8192,
            'config': '{"packs": ["codeql/java-queries"]}'
        },
        'javascript': {
            'runner': 'ubuntu-latest',
            'queries': 'security-and-quality,security-extended',
            'build-command': '',
            'threads': 2,
            'ram': 4096,
            'config': '{"packs": ["codeql/javascript-queries"]}'
        },
        'python': {
            'runner': 'ubuntu-latest',
            'queries': 'security-and-quality,security-extended',
            'build-command': '',
            'threads': 2,
            'ram': 4096,
            'config': '{"packs": ["codeql/python-queries"]}'
        },
        'go': {
            'runner': 'ubuntu-latest',
            'queries': 'security-and-quality',
            'build-command': 'go build ./...',
            'threads': 2,
            'ram': 4096,
            'config': '{"packs": ["codeql/go-queries"]}'
        },
        'cpp': {
            'runner': 'ubuntu-latest',
            'queries': 'security-and-quality',
            'build-command': 'mkdir -p build && cd build && cmake .. && make -j4',
            'threads': 4,
            'ram': 8192,
            'config': '{"packs": ["codeql/cpp-queries"]}'
        }
    }
    
    for lang in languages:
        if lang in language_configs:
            config = language_configs[lang]
            matrix_config['include'].append({
                'language': lang,
                'runner': config['runner'],
                'queries': config['queries'],
                'build-command': config['build-command'],
                'threads': config['threads'],
                'ram': config['ram'],
                'config': config['config'],
                'database_location': f'.codeql/databases/{lang}'
            })
    
    return matrix_config

if __name__ == "__main__":
    languages = detect_languages()
    matrix = generate_matrix(languages)
    print(json.dumps(matrix))

4. Advanced CodeQL Configuration

# .github/codeql/config/codeql-config.yml
name: "Advanced CodeQL Configuration"

query-filters:
  - exclude:
      id: 
        - "java/example/too-many-loops"
        - "js/debugger-statement"
        - "python/trivial-conditional"
  
  - include:
      tags:
        - "security"
        - "external/cwe/cwe-798"
        - "external/cwe/cwe-259"
        - "external/cwe/cwe-89"
        - "external/cwe/cwe-79"
  
  - include:
      precision: 
        - "high"
        - "medium"

paths:
  - "src/"
  - "lib/"
  - "app/"
  - "main/"

paths-ignore:
  - "**/test/**"
  - "**/spec/**"
  - "**/node_modules/**"
  - "**/vendor/**"
  - "**/build/**"
  - "**/dist/**"
  - "**/.cache/**"

languages:
  java:
    build-command:
      - "./gradlew build -x test"
      - "mvn compile -DskipTests"
    source-roots:
      - "src/main/java"
      - "src/main/kotlin"
  
  javascript:
    build-command: "npm run build --if-present"
    source-roots:
      - "src"
      - "lib"
  
  python:
    build-command: "python -m py_compile **/*.py"
    source-roots:
      - "src"
      - "app"
  
  go:
    build-command: "go build ./..."
    source-roots:
      - "."
  
  cpp:
    build-command: "mkdir -p build && cd build && cmake .. && make -j4"
    source-roots:
      - "src"
      - "include"

queries:
  - uses: ./.github/codeql/config/query-suites.qls
  - uses: ./.github/codeql/custom-queries/qlpack.yml

packs:
  - "codeql/java-queries"
  - "codeql/javascript-queries"
  - "codeql/python-queries"
  - "codeql/go-queries"
  - "codeql/cpp-queries"
  - "./.github/codeql/custom-queries"

database:
  location: "./.codeql/databases"
  cleanup: true
  retention-days: 30

analysis:
  mode: "${{ env.ANALYSIS_MODE || 'deep' }}"
  timeout: 300
  memory: 8192
  threads: 0  # 0 means automatic

output:
  format: sarif-latest
  include-column-numbers: true
  include-severity: true
  include-help-links: true

5. Custom Query Pack Configuration

# .github/codeql/custom-queries/qlpack.yml
name: custom-security-queries
version: 1.0.0
libraryPathDependencies:
  - codeql/java-all
  - codeql/javascript-all
  - codeql/python-all
  - codeql/go-all
  - codeql/cpp-all
extractor: |
  none
dependencies:
  codeql/java-all: "*"
  codeql/javascript-all: "*"
  codeql/python-all: "*"
  codeql/go-all: "*"
  codeql/cpp-all: "*"

6. Advanced Security Queries

// .github/codeql/custom-queries/Security/SQLInjectionAdvanced.ql
/**
 * @name Advanced SQL Injection Detection
 * @description Detects complex SQL injection patterns with taint tracking
 * @kind path-problem
 * @problem.severity error
 * @precision high
 * @id java/advanced-sql-injection
 * @tags security
 *       external/cwe/cwe-89
 *       external/cwe/cwe-564
 */

import java
import semmle.code.java.dataflow.DataFlow
import semmle.code.java.dataflow.TaintTracking
import DataFlow::PathGraph

class SqlInjectionConfiguration extends TaintTracking::Configuration {
  SqlInjectionConfiguration() { 
    this = "SqlInjectionConfiguration" 
  }
  
  override predicate isSource(DataFlow::Node source) {
    // HTTP request parameters
    exists(Method m | 
      m.hasName("getParameter") or
      m.hasName("getHeader") or
      m.hasName("getQueryString") or
      m.hasName("getCookies") or
      m.hasName("getAttribute")
    |
      source.asExpr() = m.getACall()
    ) or
    
    // File input
    exists(Method m |
      m.hasName("readLine") or
      m.hasName("read") and
      m.getDeclaringType().hasQualifiedName("java.io", "Reader")
    |
      source.asExpr() = m.getACall()
    )
  }
  
  override predicate isSink(DataFlow::Node sink) {
    // Database operations
    exists(Method m |
      m.hasName("executeQuery") or
      m.hasName("executeUpdate") or
      m.hasName("execute") or
      m.hasName("prepareStatement") or
      m.hasName("createStatement")
    |
      sink.asExpr() = m.getACall() or
      sink.asExpr() = m.getArgument(0)
    ) or
    
    // ORM operations
    exists(Method m |
      m.hasName("createNativeQuery") or
      m.hasName("createQuery") and
      m.getDeclaringType().getASupertype*().hasQualifiedName("javax.persistence", "EntityManager")
    |
      sink.asExpr() = m.getACall()
    )
  }
  
  override predicate isSanitizer(DataFlow::Node sanitizer) {
    // Parameterized queries
    exists(Method m |
      m.hasName("setString") or
      m.hasName("setInt") or
      m.hasName("setDate") and
      m.getDeclaringType().getASupertype*().hasQualifiedName("java.sql", "PreparedStatement")
    |
      sanitizer.asExpr() = m.getACall()
    ) or
    
    // Input validation
    exists(Method m |
      m.hasName("matches") or
      m.hasName("isAlphanumeric") or
      m.hasName("escapeSql")
    |
      sanitizer.asExpr() = m.getACall()
    ) or
    
    // Encoding/escaping
    exists(Method m |
      m.hasName("encode") or
      m.hasName("escape") and
      m.getDeclaringType().hasQualifiedName("org.apache.commons.lang3", "StringEscapeUtils")
    |
      sanitizer.asExpr() = m.getACall()
    )
  }
  
  override predicate isAdditionalTaintStep(DataFlow::Node node1, DataFlow::Node node2) {
    // String concatenation and manipulation
    exists(BinaryExpr bin |
      bin.getOperator() = BinaryExpr.ADD and
      (bin.getLeftOperand() = node1.asExpr() and bin.getRightOperand() = node2.asExpr() or
       bin.getRightOperand() = node1.asExpr() and bin.getLeftOperand() = node2.asExpr())
    ) or
    
    // String builder operations
    exists(MethodAccess ma |
      ma.getMethod().hasName("append") and
      ma.getMethod().getDeclaringType().getASupertype*().hasQualifiedName("java.lang", "AbstractStringBuilder") and
      node1.asExpr() = ma.getQualifier() and
      node2.asExpr() = ma
    )
  }
}

from SqlInjectionConfiguration config, DataFlow::PathNode source, DataFlow::PathNode sink
where config.hasFlowPath(source, sink)
select sink.getNode(), source, sink, 
  "Potential SQL injection vulnerability: user input flows to database operation without proper sanitization"

7. Performance Analysis Queries

// .github/codeql/custom-queries/Performance/MemoryLeakDetection.ql
/**
 * @name Memory Leak Detection
 * @description Identifies potential memory leaks in Java applications
 * @kind problem
 * @problem.severity warning
 * @precision medium
 * @id java/memory-leak-detection
 * @tags performance
 *       maintainability
 */

import java

class ResourceAllocation extends Method {
  ResourceAllocation() {
    this.getName().matches("create%") or
    this.getName().matches("new%") or
    this.getName().matches("open%") or
    this.getName().matches("allocate%") or
    this.getName().matches("init%")
  }
}

class ResourceRelease extends Method {
  ResourceRelease() {
    this.getName().matches("close%") or
    this.getName().matches("destroy%") or
    this.getName().matches("release%") or
    this.getName().matches("free%") or
    this.getName().matches("cleanup%") or
    this.getName().matches("dispose%")
  }
}

class PotentialMemoryLeak extends ResourceAllocation {
  PotentialMemoryLeak() {
    not exists(ResourceRelease release |
      release.getDeclaringType() = this.getDeclaringType() and
      release.getName().toLowerCase() = this.getName().replace("create", "close").toLowerCase() or
      release.getName().toLowerCase() = this.getName().replace("new", "delete").toLowerCase() or
      release.getName().toLowerCase() = this.getName().replace("open", "close").toLowerCase() or
      release.getName().toLowerCase() = this.getName().replace("allocate", "free").toLowerCase()
    )
  }
}

from PotentialMemoryLeak allocation
select allocation, 
  "Potential memory leak: resource allocation method '" + allocation.getName() + 
  "' without corresponding release method"

8. Security Quality Gates Workflow

# .github/workflows/codeql-security-gates.yml
name: "CodeQL Security Gates"

on:
  pull_request:
    branches: [ main, develop ]

jobs:
  security-gates:
    name: Security Quality Gates
    runs-on: ubuntu-latest
    permissions:
      security-events: write
      actions: read
      contents: read
    
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Run CodeQL Analysis
        uses: github/codeql-action/analyze@v3
        with:
          output: sarif-results
          category: "security-gates"
          upload-database: false

      - name: Check Security Thresholds
        id: security-check
        run: |
          python .github/codeql/scripts/security-gates.py

      - name: Fail on Critical Security Issues
        if: steps.security-check.outputs.critical_issues > 0
        run: |
          echo "❌ CRITICAL: ${{ steps.security-check.outputs.critical_issues }} critical security issues found"
          echo "Blocking merge due to security policy violations"
          exit 1

      - name: Warn on High Security Issues
        if: steps.security-check.outputs.high_issues > 5
        run: |
          echo "⚠️ WARNING: ${{ steps.security-check.outputs.high_issues }} high severity issues found"
          echo "Consider addressing these issues before merge"

      - name: Generate Security Report
        if: always()
        run: |
          echo "## CodeQL Security Quality Gates" >> $GITHUB_STEP_SUMMARY
          echo "### Results Summary" >> $GITHUB_STEP_SUMMARY
          echo "- βœ… Critical Issues: ${{ steps.security-check.outputs.critical_issues }}" >> $GITHUB_STEP_SUMMARY
          echo "- ⚠️ High Issues: ${{ steps.security-check.outputs.high_issues }}" >> $GITHUB_STEP_SUMMARY
          echo "- πŸ“ Medium Issues: ${{ steps.security-check.outputs.medium_issues }}" >> $GITHUB_STEP_SUMMARY
          
          if [ ${{ steps.security-check.outputs.critical_issues }} -eq 0 ]; then
            echo "### βœ… Security Gates PASSED" >> $GITHUB_STEP_SUMMARY
          else
            echo "### ❌ Security Gates FAILED" >> $GITHUB_STEP_SUMMARY
          fi

9. Security Gates Script

# .github/codeql/scripts/security-gates.py
#!/usr/bin/env python3
import json
import os
import sys
from pathlib import Path

def load_sarif_results():
    """Load and parse SARIF results from CodeQL analysis"""
    results = []
    sarif_dir = Path("sarif-results")
    
    if not sarif_dir.exists():
        return results
    
    for sarif_file in sarif_dir.glob("**/*.sarif"):
        with open(sarif_file, 'r') as f:
            data = json.load(f)
            for run in data.get('runs', []):
                results.extend(run.get('results', []))
    
    return results

def analyze_severity_distribution(results):
    """Analyze severity distribution of security issues"""
    severity_count = {
        'critical': 0,
        'high': 0,
        'medium': 0,
        'low': 0
    }
    
    for result in results:
        # Map CodeQL levels to our severity levels
        level = result.get('level', 'warning')
        if level == 'error':
            severity_count['critical'] += 1
        elif level == 'warning':
            severity_count['high'] += 1
        elif level == 'note':
            severity_count['medium'] += 1
        else:
            severity_count['low'] += 1
    
    return severity_count

def check_security_gates(severity_count):
    """Check if security gates are passed"""
    gates_passed = True
    
    # Critical issues always fail the gates
    if severity_count['critical'] > 0:
        gates_passed = False
    
    # More than 10 high issues fails the gates
    if severity_count['high'] > 10:
        gates_passed = False
    
    return gates_passed

def main():
    results = load_sarif_results()
    severity_count = analyze_severity_distribution(results)
    gates_passed = check_security_gates(severity_count)
    
    # Set output variables for GitHub Actions
    print(f"::set-output name=critical_issues::{severity_count['critical']}")
    print(f"::set-output name=high_issues::{severity_count['high']}")
    print(f"::set-output name=medium_issues::{severity_count['medium']}")
    print(f"::set-output name=low_issues::{severity_count['low']}")
    print(f"::set-output name=gates_passed::{str(gates_passed).lower()}")
    
    # Print summary
    print("Security Analysis Summary:")
    print(f"  Critical Issues: {severity_count['critical']}")
    print(f"  High Issues: {severity_count['high']}")
    print(f"  Medium Issues: {severity_count['medium']}")
    print(f"  Low Issues: {severity_count['low']}")
    print(f"  Security Gates: {'PASSED' if gates_passed else 'FAILED'}")
    
    return 0 if gates_passed else 1

if __name__ == "__main__":
    sys.exit(main())

10. Performance Configuration

# .github/codeql/config/performance-config.yml
optimization:
  max-paths: 1000
  timeout: 300
  memory: 8192
  threads: 4

analysis:
  mode: deep
  precision: balanced
  
caching:
  enabled: true
  location: ./.codeql/cache
  cleanup-age: 30d
  max-size: 10GB

logging:
  level: INFO
  queries: true
  performance: true
  timing: true

monitoring:
  enable-metrics: true
  metrics-interval: 60
  memory-usage: true

11. Query Suites Configuration

// .github/codeql/config/query-suites.qls
- description: "Security and Quality Suite"
- queries: .
  from: security-and-quality
- queries: .
  from: security-extended
- include:
    tags:
      - security
      - external/cwe/cwe-89
      - external/cwe/cwe-79
      - external/cwe/cwe-78
      - external/cwe/cwe-798
      - external/cwe/cwe-259
- exclude:
    precision: very-low
- exclude:
    kind: example

- description: "Custom Security Queries"
- queries: .
  from: custom-security-queries.qls

πŸš€ Deployment Instructions

1. Initialize the Structure

# Create directory structure
mkdir -p .github/{workflows,codeql/{config,custom-queries/{Security,Performance,Architecture},scripts}}

# Create all the files as shown above

2. Set Up Dependencies

# Install CodeQL CLI (if needed)
wget https://github.com/github/codeql-cli-binaries/releases/latest/download/codeql-linux64.zip
unzip codeql-linux64.zip
sudo mv codeql /usr/local/bin/

# Create custom query pack
cd .github/codeql/custom-queries
codeql pack init custom-security-queries

3. Commit and Push

git add .
git commit -m "feat: Add advanced CodeQL configuration"
git push origin main

πŸ”§ Key Features

βœ… Advanced Analysis Capabilities

  • Multi-language Support: Java, JavaScript, Python, Go, C++
  • Custom Query Development: Advanced security and performance queries
  • Performance Optimization: Configurable resources and caching
  • Security Quality Gates: Automated security thresholds
  • Comprehensive Reporting: Detailed security metrics and dashboards

βœ… Enterprise-Grade Security

  • Advanced Taint Tracking: Complex data flow analysis
  • Memory Leak Detection: Performance and resource management
  • SQL Injection Prevention: Comprehensive injection detection
  • Security Thresholds: Configurable quality gates

βœ… Performance Optimization

  • Parallel Execution: Multi-language concurrent analysis
  • Resource Management: Configurable memory and CPU usage
  • Caching Strategy: Reduced analysis times for subsequent runs
  • Incremental Analysis: Smart change detection

This advanced CodeQL setup provides enterprise-grade code security analysis with custom rules, performance optimization, and comprehensive security gates!


CodeAnt-AI Description

Add advanced CodeQL configuration, workflows, and custom queries

What Changed

  • Adds a comprehensive "Advanced CodeQL" guide with ready-to-use workflow YAML examples for scheduled scans, PR and push triggers, multi-language matrix runs, and OS selection.
  • Includes custom query packs and example QL rules (security, performance, memory, auth, crypto) for detecting SQL injection, weak crypto, auth bypass, expensive loops, and possible memory leaks.
  • Provides CI integration templates and helper scripts that aggregate SARIF results, upload to the security dashboard, and enforce quality gates to block merges on critical issues.

Impact

βœ… Shorter CodeQL setup time for multi-language projects
βœ… Fewer missed vulnerabilities in PRs and scheduled scans
βœ… Clearer security reports and automatic blocking on critical issues

πŸ’‘ Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

# CodeQL Advanced Implementation

## πŸš€ Complete Advanced CodeQL Setup

### 1. Advanced CodeQL Configuration Structure

```
.github/
β”œβ”€β”€ workflows/
β”‚   β”œβ”€β”€ codeql-advanced.yml
β”‚   β”œβ”€β”€ codeql-security-gates.yml
β”‚   └── codeql-custom-analysis.yml
β”œβ”€β”€ codeql/
β”‚   β”œβ”€β”€ config/
β”‚   β”‚   β”œβ”€β”€ codeql-config.yml
β”‚   β”‚   β”œβ”€β”€ query-suites.qls
β”‚   β”‚   └── performance-config.yml
β”‚   β”œβ”€β”€ custom-queries/
β”‚   β”‚   β”œβ”€β”€ qlpack.yml
β”‚   β”‚   β”œβ”€β”€ Security/
β”‚   β”‚   β”œβ”€β”€ Performance/
β”‚   β”‚   └── Architecture/
β”‚   └── scripts/
β”‚       β”œβ”€β”€ aggregate-results.py
β”‚       └── security-gates.py
```

### 2. Main Advanced CodeQL Workflow

```yaml
# .github/workflows/codeql-advanced.yml
name: "Advanced CodeQL Analysis"

on:
  push:
    branches: [ main, develop, release/* ]
    paths:
      - 'src/**'
      - 'lib/**'
      - '**.java'
      - '**.js'
      - '**.ts'
      - '**.py'
      - '**.go'
      - '**.cpp'
    paths-ignore:
      - '**/*.md'
      - '**/*.txt'
      - '**/test/**'
      - '**/spec/**'
  pull_request:
    branches: [ main, develop ]
  schedule:
    - cron: '0 2 * * 1'  # Weekly on Monday at 2 AM UTC
  workflow_dispatch:
    inputs:
      analysis-depth:
        description: 'Analysis depth level'
        required: true
        default: 'deep'
        type: choice
        options:
        - quick
        - standard
        - deep
      include-experimental:
        description: 'Include experimental queries'
        required: false
        type: boolean
        default: false

env:
  CODEQL_ACTION_VERBOSITY: info
  CODEQL_POWERFUL_ANALYSIS: true
  CODEQL_EXTRACTOR_JAVA_AGENT_DISABLE_KOTLIN: false

jobs:
  initialize:
    name: Initialize Analysis
    runs-on: ubuntu-latest
    outputs:
      matrix: ${{ steps.set-matrix.outputs.matrix }}
      database-locations: ${{ steps.set-matrix.outputs.database-locations }}
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Set up analysis matrix
        id: set-matrix
        run: |
          MATRIX_JSON=$(python .github/codeql/scripts/detect-languages.py)
          echo "matrix=$MATRIX_JSON" >> $GITHUB_OUTPUT
          echo "database-locations=$(echo $MATRIX_JSON | jq -r '.include[].database_location' | tr '\n' ',' | sed 's/,$//')" >> $GITHUB_OUTPUT

  analyze-multi-language:
    name: Analyze (${{ matrix.language }})
    needs: initialize
    runs-on: ${{ matrix.runner }}
    strategy:
      fail-fast: false
      matrix: ${{ fromJSON(needs.initialize.outputs.matrix) }}

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Initialize CodeQL
        uses: github/codeql-action/init@v3
        with:
          languages: ${{ matrix.language }}
          queries: ${{ matrix.queries }}
          config-file: ./.github/codeql/config/codeql-config.yml
          config: ${{ matrix.config }}
          tools: latest
          database: ${{ matrix.database_location }}

      - name: Build ${{ matrix.language }} code
        if: matrix.build-command
        run: ${{ matrix.build-command }}

      - name: Perform CodeQL Analysis
        uses: github/codeql-action/analyze@v3
        with:
          category: "/language:${{ matrix.language }}"
          output: sarif-results/${{ matrix.language }}
          upload-database: true
          skip-queries: ${{ github.event_name == 'schedule' && 'security' || '' }}
          threads: ${{ matrix.threads }}
          ram: ${{ matrix.ram }}
        env:
          CODEQL_RAM: ${{ matrix.ram }}
          CODEQL_THREADS: ${{ matrix.threads }}

  custom-query-analysis:
    name: Custom Query Analysis
    needs: analyze-multi-language
    runs-on: ubuntu-latest
    if: always()

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Download CodeQL databases
        run: |
          mkdir -p databases
          echo "${{ needs.initialize.outputs.database-locations }}" | tr ',' '\n' | xargs -I {} cp -r {} databases/

      - name: Run Custom Queries
        uses: github/codeql-action/analyze@v3
        with:
          queries: ./.github/codeql/custom-queries/
          packs: ./.github/codeql/custom-queries/
          output: sarif-results/custom
          category: "custom"

  security-metrics:
    name: Generate Security Metrics
    needs: [analyze-multi-language, custom-query-analysis]
    runs-on: ubuntu-latest
    if: always()

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Generate Security Report
        run: |
          python .github/codeql/scripts/aggregate-results.py

      - name: Upload Security Metrics
        uses: actions/upload-artifact@v4
        with:
          name: security-metrics
          path: |
            security-report.html
            codeql-metrics.json
          retention-days: 30

      - name: Update Security Dashboard
        run: |
          echo "## CodeQL Security Analysis Complete" >> $GITHUB_STEP_SUMMARY
          echo "βœ… Multi-language analysis completed" >> $GITHUB_STEP_SUMMARY
          echo "πŸ“Š Custom queries executed" >> $GITHUB_STEP_SUMMARY
          echo "πŸ“ˆ Security metrics generated" >> $GITHUB_STEP_SUMMARY
```

### 3. Language Detection Script

```python
# .github/codeql/scripts/detect-languages.py
#!/usr/bin/env python3
import json
import os
from pathlib import Path

def detect_languages():
    """Detect programming languages in the repository"""
    language_files = {
        'java': ['**/*.java', '**/pom.xml', '**/build.gradle', '**/build.gradle.kts'],
        'javascript': ['**/*.js', '**/*.ts', '**/package.json', '**/yarn.lock'],
        'python': ['**/*.py', '**/requirements.txt', '**/Pipfile', '**/pyproject.toml'],
        'go': ['**/*.go', '**/go.mod'],
        'cpp': ['**/*.cpp', '**/*.hpp', '**/*.c', '**/*.h', '**/CMakeLists.txt'],
    }
    
    detected_languages = []
    
    for lang, patterns in language_files.items():
        for pattern in patterns:
            if list(Path('.').glob(pattern)):
                detected_languages.append(lang)
                break
    
    # Default to javascript if no languages detected
    if not detected_languages:
        detected_languages = ['javascript']
    
    return detected_languages

def generate_matrix(languages):
    """Generate workflow matrix configuration"""
    matrix_config = {
        'include': []
    }
    
    language_configs = {
        'java': {
            'runner': 'ubuntu-latest',
            'queries': 'security-and-quality,security-extended',
            'build-command': './gradlew build -x test || mvn compile -DskipTests',
            'threads': 4,
            'ram': 8192,
            'config': '{"packs": ["codeql/java-queries"]}'
        },
        'javascript': {
            'runner': 'ubuntu-latest',
            'queries': 'security-and-quality,security-extended',
            'build-command': '',
            'threads': 2,
            'ram': 4096,
            'config': '{"packs": ["codeql/javascript-queries"]}'
        },
        'python': {
            'runner': 'ubuntu-latest',
            'queries': 'security-and-quality,security-extended',
            'build-command': '',
            'threads': 2,
            'ram': 4096,
            'config': '{"packs": ["codeql/python-queries"]}'
        },
        'go': {
            'runner': 'ubuntu-latest',
            'queries': 'security-and-quality',
            'build-command': 'go build ./...',
            'threads': 2,
            'ram': 4096,
            'config': '{"packs": ["codeql/go-queries"]}'
        },
        'cpp': {
            'runner': 'ubuntu-latest',
            'queries': 'security-and-quality',
            'build-command': 'mkdir -p build && cd build && cmake .. && make -j4',
            'threads': 4,
            'ram': 8192,
            'config': '{"packs": ["codeql/cpp-queries"]}'
        }
    }
    
    for lang in languages:
        if lang in language_configs:
            config = language_configs[lang]
            matrix_config['include'].append({
                'language': lang,
                'runner': config['runner'],
                'queries': config['queries'],
                'build-command': config['build-command'],
                'threads': config['threads'],
                'ram': config['ram'],
                'config': config['config'],
                'database_location': f'.codeql/databases/{lang}'
            })
    
    return matrix_config

if __name__ == "__main__":
    languages = detect_languages()
    matrix = generate_matrix(languages)
    print(json.dumps(matrix))
```

### 4. Advanced CodeQL Configuration

```yaml
# .github/codeql/config/codeql-config.yml
name: "Advanced CodeQL Configuration"

query-filters:
  - exclude:
      id: 
        - "java/example/too-many-loops"
        - "js/debugger-statement"
        - "python/trivial-conditional"
  
  - include:
      tags:
        - "security"
        - "external/cwe/cwe-798"
        - "external/cwe/cwe-259"
        - "external/cwe/cwe-89"
        - "external/cwe/cwe-79"
  
  - include:
      precision: 
        - "high"
        - "medium"

paths:
  - "src/"
  - "lib/"
  - "app/"
  - "main/"

paths-ignore:
  - "**/test/**"
  - "**/spec/**"
  - "**/node_modules/**"
  - "**/vendor/**"
  - "**/build/**"
  - "**/dist/**"
  - "**/.cache/**"

languages:
  java:
    build-command:
      - "./gradlew build -x test"
      - "mvn compile -DskipTests"
    source-roots:
      - "src/main/java"
      - "src/main/kotlin"
  
  javascript:
    build-command: "npm run build --if-present"
    source-roots:
      - "src"
      - "lib"
  
  python:
    build-command: "python -m py_compile **/*.py"
    source-roots:
      - "src"
      - "app"
  
  go:
    build-command: "go build ./..."
    source-roots:
      - "."
  
  cpp:
    build-command: "mkdir -p build && cd build && cmake .. && make -j4"
    source-roots:
      - "src"
      - "include"

queries:
  - uses: ./.github/codeql/config/query-suites.qls
  - uses: ./.github/codeql/custom-queries/qlpack.yml

packs:
  - "codeql/java-queries"
  - "codeql/javascript-queries"
  - "codeql/python-queries"
  - "codeql/go-queries"
  - "codeql/cpp-queries"
  - "./.github/codeql/custom-queries"

database:
  location: "./.codeql/databases"
  cleanup: true
  retention-days: 30

analysis:
  mode: "${{ env.ANALYSIS_MODE || 'deep' }}"
  timeout: 300
  memory: 8192
  threads: 0  # 0 means automatic

output:
  format: sarif-latest
  include-column-numbers: true
  include-severity: true
  include-help-links: true
```

### 5. Custom Query Pack Configuration

```yaml
# .github/codeql/custom-queries/qlpack.yml
name: custom-security-queries
version: 1.0.0
libraryPathDependencies:
  - codeql/java-all
  - codeql/javascript-all
  - codeql/python-all
  - codeql/go-all
  - codeql/cpp-all
extractor: |
  none
dependencies:
  codeql/java-all: "*"
  codeql/javascript-all: "*"
  codeql/python-all: "*"
  codeql/go-all: "*"
  codeql/cpp-all: "*"
```

### 6. Advanced Security Queries

```ql
// .github/codeql/custom-queries/Security/SQLInjectionAdvanced.ql
/**
 * @name Advanced SQL Injection Detection
 * @description Detects complex SQL injection patterns with taint tracking
 * @kind path-problem
 * @problem.severity error
 * @precision high
 * @id java/advanced-sql-injection
 * @tags security
 *       external/cwe/cwe-89
 *       external/cwe/cwe-564
 */

import java
import semmle.code.java.dataflow.DataFlow
import semmle.code.java.dataflow.TaintTracking
import DataFlow::PathGraph

class SqlInjectionConfiguration extends TaintTracking::Configuration {
  SqlInjectionConfiguration() { 
    this = "SqlInjectionConfiguration" 
  }
  
  override predicate isSource(DataFlow::Node source) {
    // HTTP request parameters
    exists(Method m | 
      m.hasName("getParameter") or
      m.hasName("getHeader") or
      m.hasName("getQueryString") or
      m.hasName("getCookies") or
      m.hasName("getAttribute")
    |
      source.asExpr() = m.getACall()
    ) or
    
    // File input
    exists(Method m |
      m.hasName("readLine") or
      m.hasName("read") and
      m.getDeclaringType().hasQualifiedName("java.io", "Reader")
    |
      source.asExpr() = m.getACall()
    )
  }
  
  override predicate isSink(DataFlow::Node sink) {
    // Database operations
    exists(Method m |
      m.hasName("executeQuery") or
      m.hasName("executeUpdate") or
      m.hasName("execute") or
      m.hasName("prepareStatement") or
      m.hasName("createStatement")
    |
      sink.asExpr() = m.getACall() or
      sink.asExpr() = m.getArgument(0)
    ) or
    
    // ORM operations
    exists(Method m |
      m.hasName("createNativeQuery") or
      m.hasName("createQuery") and
      m.getDeclaringType().getASupertype*().hasQualifiedName("javax.persistence", "EntityManager")
    |
      sink.asExpr() = m.getACall()
    )
  }
  
  override predicate isSanitizer(DataFlow::Node sanitizer) {
    // Parameterized queries
    exists(Method m |
      m.hasName("setString") or
      m.hasName("setInt") or
      m.hasName("setDate") and
      m.getDeclaringType().getASupertype*().hasQualifiedName("java.sql", "PreparedStatement")
    |
      sanitizer.asExpr() = m.getACall()
    ) or
    
    // Input validation
    exists(Method m |
      m.hasName("matches") or
      m.hasName("isAlphanumeric") or
      m.hasName("escapeSql")
    |
      sanitizer.asExpr() = m.getACall()
    ) or
    
    // Encoding/escaping
    exists(Method m |
      m.hasName("encode") or
      m.hasName("escape") and
      m.getDeclaringType().hasQualifiedName("org.apache.commons.lang3", "StringEscapeUtils")
    |
      sanitizer.asExpr() = m.getACall()
    )
  }
  
  override predicate isAdditionalTaintStep(DataFlow::Node node1, DataFlow::Node node2) {
    // String concatenation and manipulation
    exists(BinaryExpr bin |
      bin.getOperator() = BinaryExpr.ADD and
      (bin.getLeftOperand() = node1.asExpr() and bin.getRightOperand() = node2.asExpr() or
       bin.getRightOperand() = node1.asExpr() and bin.getLeftOperand() = node2.asExpr())
    ) or
    
    // String builder operations
    exists(MethodAccess ma |
      ma.getMethod().hasName("append") and
      ma.getMethod().getDeclaringType().getASupertype*().hasQualifiedName("java.lang", "AbstractStringBuilder") and
      node1.asExpr() = ma.getQualifier() and
      node2.asExpr() = ma
    )
  }
}

from SqlInjectionConfiguration config, DataFlow::PathNode source, DataFlow::PathNode sink
where config.hasFlowPath(source, sink)
select sink.getNode(), source, sink, 
  "Potential SQL injection vulnerability: user input flows to database operation without proper sanitization"
```

### 7. Performance Analysis Queries

```ql
// .github/codeql/custom-queries/Performance/MemoryLeakDetection.ql
/**
 * @name Memory Leak Detection
 * @description Identifies potential memory leaks in Java applications
 * @kind problem
 * @problem.severity warning
 * @precision medium
 * @id java/memory-leak-detection
 * @tags performance
 *       maintainability
 */

import java

class ResourceAllocation extends Method {
  ResourceAllocation() {
    this.getName().matches("create%") or
    this.getName().matches("new%") or
    this.getName().matches("open%") or
    this.getName().matches("allocate%") or
    this.getName().matches("init%")
  }
}

class ResourceRelease extends Method {
  ResourceRelease() {
    this.getName().matches("close%") or
    this.getName().matches("destroy%") or
    this.getName().matches("release%") or
    this.getName().matches("free%") or
    this.getName().matches("cleanup%") or
    this.getName().matches("dispose%")
  }
}

class PotentialMemoryLeak extends ResourceAllocation {
  PotentialMemoryLeak() {
    not exists(ResourceRelease release |
      release.getDeclaringType() = this.getDeclaringType() and
      release.getName().toLowerCase() = this.getName().replace("create", "close").toLowerCase() or
      release.getName().toLowerCase() = this.getName().replace("new", "delete").toLowerCase() or
      release.getName().toLowerCase() = this.getName().replace("open", "close").toLowerCase() or
      release.getName().toLowerCase() = this.getName().replace("allocate", "free").toLowerCase()
    )
  }
}

from PotentialMemoryLeak allocation
select allocation, 
  "Potential memory leak: resource allocation method '" + allocation.getName() + 
  "' without corresponding release method"
```

### 8. Security Quality Gates Workflow

```yaml
# .github/workflows/codeql-security-gates.yml
name: "CodeQL Security Gates"

on:
  pull_request:
    branches: [ main, develop ]

jobs:
  security-gates:
    name: Security Quality Gates
    runs-on: ubuntu-latest
    permissions:
      security-events: write
      actions: read
      contents: read
    
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Run CodeQL Analysis
        uses: github/codeql-action/analyze@v3
        with:
          output: sarif-results
          category: "security-gates"
          upload-database: false

      - name: Check Security Thresholds
        id: security-check
        run: |
          python .github/codeql/scripts/security-gates.py

      - name: Fail on Critical Security Issues
        if: steps.security-check.outputs.critical_issues > 0
        run: |
          echo "❌ CRITICAL: ${{ steps.security-check.outputs.critical_issues }} critical security issues found"
          echo "Blocking merge due to security policy violations"
          exit 1

      - name: Warn on High Security Issues
        if: steps.security-check.outputs.high_issues > 5
        run: |
          echo "⚠️ WARNING: ${{ steps.security-check.outputs.high_issues }} high severity issues found"
          echo "Consider addressing these issues before merge"

      - name: Generate Security Report
        if: always()
        run: |
          echo "## CodeQL Security Quality Gates" >> $GITHUB_STEP_SUMMARY
          echo "### Results Summary" >> $GITHUB_STEP_SUMMARY
          echo "- βœ… Critical Issues: ${{ steps.security-check.outputs.critical_issues }}" >> $GITHUB_STEP_SUMMARY
          echo "- ⚠️ High Issues: ${{ steps.security-check.outputs.high_issues }}" >> $GITHUB_STEP_SUMMARY
          echo "- πŸ“ Medium Issues: ${{ steps.security-check.outputs.medium_issues }}" >> $GITHUB_STEP_SUMMARY
          
          if [ ${{ steps.security-check.outputs.critical_issues }} -eq 0 ]; then
            echo "### βœ… Security Gates PASSED" >> $GITHUB_STEP_SUMMARY
          else
            echo "### ❌ Security Gates FAILED" >> $GITHUB_STEP_SUMMARY
          fi
```

### 9. Security Gates Script

```python
# .github/codeql/scripts/security-gates.py
#!/usr/bin/env python3
import json
import os
import sys
from pathlib import Path

def load_sarif_results():
    """Load and parse SARIF results from CodeQL analysis"""
    results = []
    sarif_dir = Path("sarif-results")
    
    if not sarif_dir.exists():
        return results
    
    for sarif_file in sarif_dir.glob("**/*.sarif"):
        with open(sarif_file, 'r') as f:
            data = json.load(f)
            for run in data.get('runs', []):
                results.extend(run.get('results', []))
    
    return results

def analyze_severity_distribution(results):
    """Analyze severity distribution of security issues"""
    severity_count = {
        'critical': 0,
        'high': 0,
        'medium': 0,
        'low': 0
    }
    
    for result in results:
        # Map CodeQL levels to our severity levels
        level = result.get('level', 'warning')
        if level == 'error':
            severity_count['critical'] += 1
        elif level == 'warning':
            severity_count['high'] += 1
        elif level == 'note':
            severity_count['medium'] += 1
        else:
            severity_count['low'] += 1
    
    return severity_count

def check_security_gates(severity_count):
    """Check if security gates are passed"""
    gates_passed = True
    
    # Critical issues always fail the gates
    if severity_count['critical'] > 0:
        gates_passed = False
    
    # More than 10 high issues fails the gates
    if severity_count['high'] > 10:
        gates_passed = False
    
    return gates_passed

def main():
    results = load_sarif_results()
    severity_count = analyze_severity_distribution(results)
    gates_passed = check_security_gates(severity_count)
    
    # Set output variables for GitHub Actions
    print(f"::set-output name=critical_issues::{severity_count['critical']}")
    print(f"::set-output name=high_issues::{severity_count['high']}")
    print(f"::set-output name=medium_issues::{severity_count['medium']}")
    print(f"::set-output name=low_issues::{severity_count['low']}")
    print(f"::set-output name=gates_passed::{str(gates_passed).lower()}")
    
    # Print summary
    print("Security Analysis Summary:")
    print(f"  Critical Issues: {severity_count['critical']}")
    print(f"  High Issues: {severity_count['high']}")
    print(f"  Medium Issues: {severity_count['medium']}")
    print(f"  Low Issues: {severity_count['low']}")
    print(f"  Security Gates: {'PASSED' if gates_passed else 'FAILED'}")
    
    return 0 if gates_passed else 1

if __name__ == "__main__":
    sys.exit(main())
```

### 10. Performance Configuration

```yaml
# .github/codeql/config/performance-config.yml
optimization:
  max-paths: 1000
  timeout: 300
  memory: 8192
  threads: 4

analysis:
  mode: deep
  precision: balanced
  
caching:
  enabled: true
  location: ./.codeql/cache
  cleanup-age: 30d
  max-size: 10GB

logging:
  level: INFO
  queries: true
  performance: true
  timing: true

monitoring:
  enable-metrics: true
  metrics-interval: 60
  memory-usage: true
```

### 11. Query Suites Configuration

```ql
// .github/codeql/config/query-suites.qls
- description: "Security and Quality Suite"
- queries: .
  from: security-and-quality
- queries: .
  from: security-extended
- include:
    tags:
      - security
      - external/cwe/cwe-89
      - external/cwe/cwe-79
      - external/cwe/cwe-78
      - external/cwe/cwe-798
      - external/cwe/cwe-259
- exclude:
    precision: very-low
- exclude:
    kind: example

- description: "Custom Security Queries"
- queries: .
  from: custom-security-queries.qls
```

## πŸš€ Deployment Instructions

### 1. Initialize the Structure
```bash
# Create directory structure
mkdir -p .github/{workflows,codeql/{config,custom-queries/{Security,Performance,Architecture},scripts}}

# Create all the files as shown above
```

### 2. Set Up Dependencies
```bash
# Install CodeQL CLI (if needed)
wget https://github.com/github/codeql-cli-binaries/releases/latest/download/codeql-linux64.zip
unzip codeql-linux64.zip
sudo mv codeql /usr/local/bin/

# Create custom query pack
cd .github/codeql/custom-queries
codeql pack init custom-security-queries
```

### 3. Commit and Push
```bash
git add .
git commit -m "feat: Add advanced CodeQL configuration"
git push origin main
```

## πŸ”§ Key Features

### βœ… Advanced Analysis Capabilities
- **Multi-language Support**: Java, JavaScript, Python, Go, C++
- **Custom Query Development**: Advanced security and performance queries
- **Performance Optimization**: Configurable resources and caching
- **Security Quality Gates**: Automated security thresholds
- **Comprehensive Reporting**: Detailed security metrics and dashboards

### βœ… Enterprise-Grade Security
- **Advanced Taint Tracking**: Complex data flow analysis
- **Memory Leak Detection**: Performance and resource management
- **SQL Injection Prevention**: Comprehensive injection detection
- **Security Thresholds**: Configurable quality gates

### βœ… Performance Optimization
- **Parallel Execution**: Multi-language concurrent analysis
- **Resource Management**: Configurable memory and CPU usage
- **Caching Strategy**: Reduced analysis times for subsequent runs
- **Incremental Analysis**: Smart change detection

This advanced CodeQL setup provides enterprise-grade code security analysis with custom rules, performance optimization, and comprehensive security gates!
@Sazwanismail Sazwanismail added this to the Create CodeQL Advanced milestone Nov 11, 2025
@Sazwanismail Sazwanismail self-assigned this Nov 11, 2025
@Sazwanismail Sazwanismail added bug Something isn't working documentation Improvements or additions to documentation duplicate This issue or pull request already exists enhancement New feature or request labels Nov 11, 2025
@Sazwanismail Sazwanismail added help wanted Extra attention is needed question Further information is requested wontfix This will not be worked on labels Nov 11, 2025
@codeant-ai
Copy link

codeant-ai bot commented Nov 11, 2025

CodeAnt AI is reviewing your PR.


Thanks for using CodeAnt! πŸŽ‰

We're free for open-source projects. if you're enjoying it, help us grow by sharing.

Share on X Β·
Reddit Β·
LinkedIn

@Sazwanismail Sazwanismail merged commit 2257b49 into master Nov 11, 2025
4 of 19 checks passed
@codeant-ai codeant-ai bot added the size:XL This PR changes 500-999 lines, ignoring generated files label Nov 11, 2025
@codeant-ai
Copy link

codeant-ai bot commented Nov 11, 2025

CodeAnt AI finished reviewing your PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working documentation Improvements or additions to documentation duplicate This issue or pull request already exists enhancement New feature or request help wanted Extra attention is needed question Further information is requested size:XL This PR changes 500-999 lines, ignoring generated files wontfix This will not be worked on

Projects

Development

Successfully merging this pull request may close these issues.

2 participants