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:
# 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:
# 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
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
# .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 }}"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:
$ 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:
- Remove the secret (recommended) - Remove the secret from your code, use
git rebase -ito rewrite history, and push again - 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
- Mark as used in tests - If the secret is intentionally used in a test fixture, you can allow it with documentation
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.
# .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: alwaysThe 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:
| Pattern | Example | Copilot's Suggestion |
|---|---|---|
| Hardcoded credentials | password = "admin123" | Use environment variables or a secrets manager |
| Missing input validation | User input passed directly to file operations | Add path sanitization and allowlist validation |
| Insecure randomness | Math.random() for tokens | Use crypto.randomBytes() for security-sensitive values |
| Missing rate limiting | Authentication endpoint without throttling | Add rate limiting middleware to prevent brute force |
| Overly permissive CORS | Access-Control-Allow-Origin: * | Restrict to specific trusted origins |
| Unsafe deserialization | pickle.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
# .github/copilot-content-exclusions.yml # Prevent Copilot from accessing sensitive files exclude: - "**/.env*" - "**/secrets/**" - "**/certificates/**" - "**/security-config/**" - "**/*credentials*" - "**/*private-key*"
Ready to Go Deeper?
Live instructor-led courses from our partners. Affiliate disclosure.
AI & ML Courses - 30% Off
Live instructor-led AI, machine learning, data science, and cloud courses for working professionals. Use code Limited30 at checkout.
EdurekaDataCamp - AI & Data Science
Hands-on Python, machine learning, and AI courses with interactive exercises and real projects.
DataCampedX - Top AI Courses
University-level AI courses from MIT, Harvard, Stanford. Earn certificates that employers recognize.
edX