Home
IT Hub

A Guide to GitHub Security APIs for Enhancing Repository Security

GitHub
Reco Security Experts
Updated
December 16, 2024
December 19, 2024

GitHub is one of the most widely used platforms for collaborative software development, with millions of developers contributing to open-source projects. With this immense growth, the potential risks associated with code vulnerabilities also increase, making security management an indispensable part of the development process. This is where GitHub Security APIs come into play. By providing programmatic access to security features, GitHub Security APIs help developers and security teams identify, monitor, and manage vulnerabilities effectively.

In this guide, we'll focus on the technical aspects of GitHub Security APIs, including their endpoints, request parameters, authentication methods, and practical use cases. This resource is intended for developers, security analysts, and system architects who wish to understand and use GitHub Security APIs to secure their code.

Introduction to GitHub Security APIs

GitHub Security APIs provide endpoints for interacting with GitHub's security advisories, allowing for the automation of critical security management tasks such as vulnerability monitoring, security advisory creation, and CVE requests. By understanding and leveraging these APIs, developers can incorporate security practices directly into their workflows and CI/CD pipelines.

The most common security-related actions facilitated by these APIs include retrieving security advisories, managing repository-level advisories, requesting CVE identification numbers, and automating alerts for vulnerabilities.

The core GitHub Security APIs include the Global Security Advisory API, the Repository Security Advisory API, and the Secret Scanning API. Here, we'll dive deeper into how to use these APIs effectively for different use cases.

How to Generate a GitHub Bearer Access Token

Generating a Bearer access token allows you to authenticate with GitHub's API securely. Below, we walk you through the steps to create a personal access token.

Step 1: Log in to Your GitHub Account

First, log in to your GitHub account using your credentials.

Step 2: Access Settings

Once logged in, click on your profile picture in the top right corner and select Settings from the dropdown menu.

Step 3: Navigate to Developer Settings

Scroll down the left-hand sidebar and click on Developer settings. This option is located near the bottom.

The screenshot shows the steps to access developer settings in GitHub, highlighting the navigation path to find and select the developer settings option.

Step 4: Go to Personal Access Tokens

Click on Personal access tokens, then select Tokens (classic).

Screenshot of GitHub Developer Settings, highlighting the option to navigate to Personal Access Tokens for managing API access and authentication.

In the GitHub developer settings, first, select 'personal access token,' then choose the 'classic' option to proceed with generating an access token. 

Step 5: Generate a New Token (Classic)

Click on Generate new token to create a new personal access token.

In GitHub developer settings, click on 'Generate new token' under the 'classic' option to create a new personal access token.

Step 6: Configure the Token

  • Note: Provide a description of the token to help you remember its purpose.
  • Expiration: Set an expiration period for the token as per your security needs.
  • Scopes: Select the necessary scopes for the token. Scopes define the permissions granted by this token, such as repository access or user data.

After filling in the required fields, click on the Generate token.

Configure your GitHub token by adding a description, setting an expiration, selecting scopes, and clicking 'Generate token' to create it.

Step 7: Copy the Token

Once the token is generated, make sure to copy it somewhere safe. You will not be able to view the token again once you navigate away from the page.

After generating the token in GitHub, ensure you copy it to a safe place, as you will not be able to view it again once you leave the page.

Using the Token for Authentication

You can use this generated token to authenticate API requests when using GitHub's API. The token is used as a Bearer token, providing secure access.

This token can be used to:

  • Authenticate GitHub API requests in your code by adding the token in the authorization header.
  • Access GitHub API using tools like Postman or other API testing utilities.

Adding the Token as a Bearer

In any API request, you can include the Bearer token in the headers like so:

Authorization: Bearer <YOUR_GENERATED_TOKEN>

This ensures that GitHub can authenticate and authorize the request based on the scopes you selected.

Base URL for GitHub API

  • Base URL: https://api.github.com/

Use this base URL in combination with the relevant API endpoints to interact with GitHub's services.

Global Security Advisories API

The Global Security Advisories API allows users to retrieve details about security advisories that have been registered in GitHub's advisory database. You can access detailed information regarding the advisories, such as Common Vulnerabilities and Exposures (CVE) IDs, severity, ecosystem, and more.

Endpoint: List Global Security Advisories

  • URL: GET /advisories
  • Description: Lists all global security advisories that match the specified parameters.

Example Request:

curl -L \
  -H "Accept: application/vnd.github+json" \
  -H "Authorization: Bearer <YOUR-TOKEN>" \
  https://api.github.com/advisories

Parameters:

  • Accept (string): Setting to application/vnd.github+json is recommended.
  • Type (string): Defines the type of advisory (e.g., reviewed, malware, unreviewed). By default, only reviewed advisories are returned.
  • Severity (string): Filters advisories by severity (low, medium, high, critical).
  • Ecosystem (string): Returns advisories related to specific package ecosystems such as npm, pip, maven, etc.

This endpoint is particularly useful for aggregating advisories across all repositories and ecosystems to understand broader security trends.

Example Response:

This documentation provides an example response from a GitHub security advisory API database. 

This information can be used to alert teams about ongoing vulnerabilities that could potentially affect their projects.

Using Pagination for Large Data Retrieval

When working with large datasets, such as a list of security advisories, using pagination ensures that API calls remain efficient and manageable.

Pagination Parameters

  • per_page (integer): Specifies how many advisories to return per page. The default is 30, with a maximum of 100.
  • before/after (string): Use cursor-based pagination to retrieve advisories before or after a specific point in time.

Here's an example of using pagination to navigate through advisories:

curl -L \
  -H "Accept: application/vnd.github+json" \
  -H "Authorization: Bearer <YOUR-TOKEN>" \
  'https://api.github.com/advisories?per_page=50&after=cursor123'

This way, you can efficiently fetch advisories without overwhelming the server or hitting rate limits.

Repository Security Advisories API: Managing Vulnerabilities

The Repository Security Advisories API provides tools for managing security advisories related to specific repositories. This API lets users create, view, update, or delete advisories within their repositories. These features are invaluable for maintaining security at the repository level, allowing developers to stay informed about vulnerabilities that may affect their projects.

Endpoint: List Repository Security Advisories

  • URL: GET /repos/{owner}/{repo}/security-advisories
  • Description: Lists all security advisories within a specific repository, allowing maintainers to track and manage vulnerabilities effectively.

Example Request:

curl -L \
  -H "Accept: application/vnd.github+json" \
  -H "Authorization: Bearer <YOUR-TOKEN>" \
  https://api.github.com/repos/OWNER/REPO/security-advisories

Parameters:

  • accept (string): Set to application/vnd.github+json.
  • state (string): Filter advisories by their state (triage, draft, published, closed).
  • sort (string): Sort results by created, updated, or published.
  • per_page (integer): Define how many results per page should be returned (maximum 100).

Example Response:

A screenshot provides an example response from a security advisory API in GitHub.

These advisories can then be used to track vulnerabilities within your repositories. This proactive approach is crucial for maintaining repository integrity and ensuring that security issues are addressed promptly, thereby reducing the risk of exploitation.

Creating and Managing Repository Security Advisories

Creating and managing repository security advisories is one of the core features provided by the Repository Security Advisory API. It allows maintainers to create advisories for vulnerabilities in their repositories, making it possible to communicate these issues securely among trusted contributors before making them public.

Endpoint: Create a Repository Security Advisory

  • URL: POST /repos/{owner}/{repo}/security-advisories
  • Description: Creates a new security advisory in the specified repository, typically initially in a draft state.

Example Request:

curl -L \
  -H "Accept: application/vnd.github+json" \
  -H "Authorization: Bearer <YOUR-TOKEN>" \
  https://api.github.com/repos/OWNER/REPO/security-advisories \
  -d '{
    "summary": "Critical vulnerability in Z component,”
    "description": "Detailed information about the impact of the vulnerability.”
    "severity": "critical",
    "cve_id": null,
    "vulnerabilities": [
      {
        "package": {
          "name": "componentZ",
          "ecosystem": "pip"
        },
        "vulnerable_version_range": "< 2.0.0",
        "patched_versions": "2.0.0"
      }
    ]
  }'

Parameters:

  • Summary (string, required): Short description of the advisory.
  • Description (string, required): Detailed description explaining the vulnerability.
  • Severity (string): Defines the severity (low, medium, high, critical).
  • Vulnerabilities (array of objects required): Information on packages affected by the vulnerability.

The advisory is created in the draft state by default, meaning it will only be accessible to repository collaborators until published. This draft feature is useful for privately coordinating fixes before public disclosure.

Requesting CVE Identifiers for Repository Security Advisories

CVE (Common Vulnerabilities and Exposures) identifiers are a standard way to refer to specific vulnerabilities. If your advisory needs a CVE ID, GitHub provides a simple method to request one through their API. Having a CVE ID allows for better tracking and visibility across the wider cybersecurity community.

Endpoint: Request a CVE

  • URL: POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve
  • Description: Requests a CVE ID for a security advisory, enabling it to be identified in the CVE database.

Example Request:

curl -L \
  -H "Accept: application/vnd.github+json" \
  -H "Authorization: Bearer <YOUR-TOKEN>" \
  https://api.github.com/repos/OWNER/REPO/security-advisories/{ghsa_id}/cve

Upon acceptance, the vulnerability will receive a unique CVE identifier, which can be used to track and address the vulnerability across multiple platforms. CVE IDs are instrumental for transparency and building trust within the developer and user communities.

Integrating GitHub Security APIs into CI/CD Pipelines

Integrating GitHub Security APIs into your CI/CD pipelines provides automated security checks, helping you ensure that any new code changes do not introduce vulnerabilities in your application. This automation is crucial for maintaining code integrity and ensuring that security practices are part of the development workflow.

GitHub Actions can be used to automate security checks in your CI/CD pipeline. Below is an example workflow that integrates security advisories:

name: Security Advisory Check

on:
  push:
    branches:
      - main

jobs:
  advisory-check:
    runs-on: ubuntu-latest
    steps:
      - name: Check out the repository
        uses: actions/checkout@v2

      - name: List repository advisories
        run: |
          curl -L \
            -H "Accept: application/vnd.github+json" \
            -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
            https://api.github.com/repos/${{ github.repository }}/security-advisories 

By incorporating this into your CI/CD pipeline, you can automate security advisory checks as part of the development lifecycle. This helps maintain a secure environment where potential vulnerabilities are caught early.

Best Practices for Authentication and Access Control

Using the GitHub Security APIs securely requires proper authentication and permissions. GitHub recommends using fine-grained personal access tokens or GitHub App tokens to limit access and ensure secure usage.

Key Recommendations:

  • Use GitHub App user access tokens for project-specific API access, ensuring that tokens have limited scope and permissions.
  • Limit token scopes to only the permissions required for the job, such as read or write access to specific repositories.
  • Regularly rotate access tokens to prevent misuse in case of exposure.

Fine-grained tokens allow you to specify permissions like read/write access to repository advisories, ensuring that even if a token is compromised, the damage remains limited. Implementing these practices will help secure your use of GitHub APIs while minimizing risk.

Conclusion

GitHub Security APIs provide the power to integrate comprehensive security controls into your software development lifecycle. By understanding and leveraging these APIs, developers can automate security monitoring, identify vulnerabilities proactively, and maintain high standards for code security. The key to using these APIs effectively is integrating them into CI/CD processes and following best practices for authentication and permission management.

Additionally, by combining automation and API capabilities with effective practices like access control and continuous monitoring, development teams can better mitigate risks and ensure secure, stable codebases. As the software ecosystem continues to evolve, integrating security into every step of development will become increasingly important. GitHub Security APIs offer the right tools to achieve this and ensure your projects remain secure.

Explore More
See more articles from our Hub

Start Securing Your Entire SaaS Lifecycle

Request a demo