Intermediate

AI-Powered Security

Learn how GitHub uses AI to find vulnerabilities, generate fixes, detect secrets, and protect your codebase - automatically and at scale.

Copilot Autofix for Security Vulnerabilities

Copilot Autofix is one of the most impactful AI security features on GitHub. When GitHub's code scanning (powered by CodeQL) detects a vulnerability in your code, Copilot Autofix automatically generates a fix suggestion - not just a description of the problem, but actual code changes you can apply with one click.

Here is how it works in practice. Suppose CodeQL detects an SQL injection vulnerability in your Python code:

Python
# VULNERABLE: SQL injection via string concatenation
@app.route('/users')
def get_user():
    username = request.args.get('username')
    query = f"SELECT * FROM users WHERE name = '{username}'"
    cursor.execute(query)
    return jsonify(cursor.fetchall())

Copilot Autofix analyzes the alert, understands the vulnerability pattern, and generates a fix:

Python
# FIXED: Parameterized query prevents SQL injection
@app.route('/users')
def get_user():
    username = request.args.get('username')
    query = "SELECT * FROM users WHERE name = %s"
    cursor.execute(query, (username,))
    return jsonify(cursor.fetchall())

The fix appears directly in the code scanning alert on GitHub.com and in pull request reviews. You can review the suggested change, modify it if needed, and commit it - all without leaving the browser. Copilot Autofix supports the most common vulnerability categories:

  • Injection flaws - SQL injection, command injection, LDAP injection, XPath injection
  • Cross-site scripting (XSS) - Reflected, stored, and DOM-based XSS
  • Path traversal - Directory traversal and file inclusion vulnerabilities
  • Authentication issues - Weak cryptography, missing authentication checks
  • Deserialization - Unsafe deserialization of user-controlled data
  • Server-side request forgery (SSRF) - Unvalidated URL redirects and server-side requests
Key takeaway: Copilot Autofix reduces the mean time to remediate security vulnerabilities from weeks to minutes. In GitHub's data, repositories using Autofix fix vulnerabilities 3x faster than those that rely on manual remediation alone.

GitHub Advanced Security with AI

GitHub Advanced Security (GHAS) is the umbrella platform that combines code scanning, secret scanning, and dependency review. AI enhances each of these capabilities, turning them from alert generators into intelligent assistants that help you prioritize and fix issues.

The AI-enhanced security overview dashboard provides:

  • Risk prioritization - AI ranks vulnerabilities by exploitability, not just severity. A medium-severity vulnerability in a public-facing endpoint is prioritized over a critical vulnerability in dead code
  • Trend analysis - AI identifies patterns in your security posture over time, flagging when new categories of vulnerabilities are being introduced
  • Fix coverage - Shows what percentage of alerts have Autofix suggestions available, helping you focus manual effort on the ones that cannot be auto-fixed

Enabling GHAS on Your Repository

YAML
# .github/workflows/codeql-analysis.yml
name: CodeQL Analysis
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
  schedule:
    - cron: '0 6 * * 1'  # Weekly scan on Monday at 6am

jobs:
  analyze:
    runs-on: ubuntu-latest
    permissions:
      actions: read
      contents: read
      security-events: write

    strategy:
      matrix:
        language: ['javascript', 'python']

    steps:
      - uses: actions/checkout@v4

      - name: Initialize CodeQL
        uses: github/codeql-action/init@v3
        with:
          languages: ${{ matrix.language }}
          # Enable AI-powered extended queries for deeper analysis
          queries: security-extended

      - name: Auto-build
        uses: github/codeql-action/autobuild@v3

      - name: Perform CodeQL Analysis
        uses: github/codeql-action/analyze@v3
        with:
          category: "/language:${{ matrix.language }}"
💡
Good to know: GitHub Advanced Security is free for public repositories. For private repositories, it requires a GitHub Enterprise plan with the GHAS add-on. However, secret scanning and push protection are available for free on all public repositories.

Secret Scanning and Push Protection

Secret scanning uses pattern matching and AI to detect credentials, API keys, tokens, and other secrets that have been accidentally committed to your repository. Push protection takes this a step further by blocking pushes that contain detected secrets before they ever reach GitHub.

How AI Enhances Secret Scanning

Traditional secret scanning relies on known patterns (regex for AWS keys, GitHub tokens, etc.). AI-powered secret scanning adds two critical capabilities:

  • Generic secret detection - AI identifies high-entropy strings that look like secrets even when they do not match a known provider pattern. This catches custom API keys, internal tokens, and passwords that would otherwise slip through
  • False positive reduction - AI analyzes the context around detected strings to determine if they are actually secrets or just test fixtures, documentation examples, or hash values. This dramatically reduces alert noise

What Happens When Push Protection Triggers

When you try to push a commit containing a detected secret, Git returns an error with specific details:

Bash
$ git push origin main

remote: error: GH013: Repository rule violations found for refs/heads/main.
remote:
remote: --  Push cannot contain secrets  --
remote:
remote:  (?) To push, remove secret from commit(s) or follow this URL to allow the secret.
remote:
remote: GITHUB PUSH PROTECTION
remote:   -----------------------------------------
remote:    Detected secret: GitHub Personal Access Token
remote:    Location: src/config.js:15
remote:    Secret type: github_personal_access_token
remote:
remote:    To fix: Remove the secret and use environment
remote:    variables or a secrets manager instead.
remote:   -----------------------------------------

You have three options when push protection triggers:

  1. Remove the secret (recommended) - Remove the secret from your code, use git rebase -i to rewrite history, and push again
  2. Mark as false positive - If the detected string is not actually a secret (e.g., a test token), you can bypass with a reason that gets logged for audit
  3. Mark as used in tests - If the secret is intentionally used in a test fixture, you can allow it with documentation
Warning: If a secret has already been pushed to GitHub, rotating the credential is mandatory - even if you immediately delete it. The secret exists in Git history and may have been cached, forked, or scraped. Always assume a pushed secret is compromised.

Dependency Review with AI Recommendations

When a pull request adds or updates dependencies, GitHub's dependency review automatically analyzes the changes and flags known vulnerabilities. AI enhances this by providing context-aware recommendations.

YAML
# .github/workflows/dependency-review.yml
name: Dependency Review
on: [pull_request]

permissions:
  contents: read
  pull-requests: write

jobs:
  dependency-review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Dependency Review
        uses: actions/dependency-review-action@v4
        with:
          # Block PRs that introduce critical or high vulnerabilities
          fail-on-severity: high
          # Also check license compatibility
          deny-licenses: GPL-3.0, AGPL-3.0
          # Comment on PR with findings
          comment-summary-in-pr: always

The AI-enhanced dependency review provides:

  • Vulnerability context - Not just "this package has a CVE," but whether the vulnerable function is actually called in your code
  • Upgrade path suggestions - Recommends the minimum version upgrade needed to resolve the vulnerability, considering compatibility
  • Alternative packages - When a dependency has persistent security issues, suggests well-maintained alternatives
  • Transitive dependency analysis - Identifies when vulnerabilities come from indirect dependencies and suggests which direct dependency to update

Copilot Security Suggestions in Code Reviews

When Copilot reviews pull requests (available with Copilot Enterprise), it specifically looks for security patterns in addition to general code quality. These security-focused suggestions appear inline in the PR diff, making them easy to address during the normal review flow.

Common security patterns Copilot flags during code review:

PatternExampleCopilot's Suggestion
Hardcoded credentialspassword = "admin123"Use environment variables or a secrets manager
Missing input validationUser input passed directly to file operationsAdd path sanitization and allowlist validation
Insecure randomnessMath.random() for tokensUse crypto.randomBytes() for security-sensitive values
Missing rate limitingAuthentication endpoint without throttlingAdd rate limiting middleware to prevent brute force
Overly permissive CORSAccess-Control-Allow-Origin: *Restrict to specific trusted origins
Unsafe deserializationpickle.loads(user_data)Use json.loads() or validate input before deserializing

Security Best Practices for AI-Assisted Development

Using AI tools like Copilot introduces new security considerations. AI-generated code can contain vulnerabilities just like human-written code - and sometimes more frequently because the model may reproduce insecure patterns from its training data. Here are essential practices to follow:

When Using Copilot to Write Code

  • Always review security-sensitive code - Never blindly accept Copilot suggestions for authentication, authorization, cryptography, input validation, or database queries
  • Provide security context in prompts - When asking Copilot to write code, explicitly mention security requirements: "Write a login endpoint with rate limiting, parameterized queries, and bcrypt password hashing"
  • Enable code scanning on all repositories - This catches vulnerabilities that slip through human review, whether the code was written by a human or AI
  • Use Copilot to audit existing code - Ask Copilot Chat to review code for security issues: "Review this function for SQL injection, XSS, and authentication bypass vulnerabilities"

Organizational Security Policies

  • Configure Copilot content exclusions - Prevent Copilot from accessing sensitive files (credentials, certificates, security configurations) by configuring content exclusions in your organization settings
  • Enable audit logging - Track how AI tools are used across your organization, which suggestions are accepted, and which files are accessed
  • Set up branch protection rules - Require code scanning checks to pass before merging, ensuring AI-generated code meets the same security bar as human code
  • Train your team - Ensure developers understand that AI-generated code must be reviewed with the same rigor as code from any other source
YAML
# .github/copilot-content-exclusions.yml
# Prevent Copilot from accessing sensitive files
exclude:
  - "**/.env*"
  - "**/secrets/**"
  - "**/certificates/**"
  - "**/security-config/**"
  - "**/*credentials*"
  - "**/*private-key*"
Key takeaway: AI security tools work best as layers of defense, not replacements for security practices. Use Copilot Autofix to remediate quickly, code scanning to catch what humans miss, secret scanning to prevent credential leaks, and dependency review to manage supply chain risk. Together, they create a security posture that improves continuously.

Ready to Go Deeper?

Live instructor-led courses from our partners. Affiliate disclosure.