Playing with GitHub Secret API

Reading Time: 7 minutes

In GitHub actions we use some sensitive information. That could be at any level like organization, repository, or repository environments.
So GitHub allow you to store that sensitive information in the form of secrets.

Example: We use GitHub’s global variables. For e.g. AWS credentials (AWS_ACCESS_KEY, AWS_SECRET_KEY) to authenticate deployments.

So this secrets can be managed through GitHub UI.

In this BLOG, we will see a solution that must provide something similar, including support to update via API calls.

Solution: GitHub Secret API

The GitHub Secrets API lets you create, update an delete in addition retrieve information about encrypted secrets. Encrypted secrets allow you to store sensitive information. Such as access tokens, in your repository, repository environments also organization.

This API is only available to authenticated users. So you need to create the Personal Access Token. To create the access token you can refer to this.

Access tokens require repo scope for private repos and public_repo scope for public repos.

Now, we’ll see the different operations perform using GitHub Secret API at an organization level.

1. List organization Secrets

Lists all secrets available in an organization. However without revealing their encrypted values. And you need to provide the access token and the org name to the following API.

GET /orgs/{org}/actions/secrets

Parameters:

NameTypeInDescription
acceptstringheaderSetting to application/vnd.github.v3+json is recommended.
orgstringpath 
per_pagestringqueryResults per page (max 100).
pagestringqueryPage number of the results to fetch.

Example:

curl \
  -X GET \
  -H "Accept: application/vnd.github.v3+json" \
  -u sakshigawande12:c08e2159331343703c2f6581840d2871cbd53ca9 \
   https://api.github.com/orgs/knoldus-test/actions/secrets

Response:

{
  "total_count": 3,
  "secrets": [
    {
      "name": "CREATED_SECRET",
      "created_at": "2021-03-26T11:36:40Z",
      "updated_at": "2021-03-26T11:36:40Z",
      "visibility": "all"
    },
    {
      "name": "DOCKERHUB_PASSWORD",
      "created_at": "2021-03-26T07:26:20Z",
      "updated_at": "2021-03-26T07:26:20Z",
      "visibility": "all"
    },
    {
      "name": "DOCKERHUB_USERNAME",
      "created_at": "2021-03-26T07:24:33Z",
      "updated_at": "2021-03-26T07:24:33Z",
      "visibility": "all"
    }
  ]
}

2. Get an organization public key

This api will return an encrypted public key with the key_id. Which will use at the time of creating/updating the secrets.

GET /orgs/{org}/actions/secrets/public-key

Parameters:

NameTypeInDescription
acceptstringheaderSetting to application/vnd.github.v3+json is recommended.
orgstringpath 

Example:

curl \
  -H "Accept: application/vnd.github.v3+json" \
  -u sakshigawande:c08e2159331343703c2f6581840d2871cbd53ca9 \
  https://api.github.com/orgs/knoldus-test/actions/secrets/public-key

Response:

{
  "key_id": "568250167242549743",
  "key": "IBzPt04+l7NnRChHTTek48p836MmldQjzDk/R9rNg1Q="
}

3. Get an organization secret

Using this API ,you will be an able to gets a single organization secret without revealing its encrypted value. You need to provide the name of the secret . Similarly the access token for authentication to the following API.

GET /orgs/{org}/actions/secrets/{secret_name}

Parameters:

NameTypeInDescription
acceptstringheaderSetting to application/vnd.github.v3+json is recommended.
orgstringpath 
secret_namestringpathsecret_name parameter

Example:

curl \
  -H "Accept: application/vnd.github.v3+json" \
    -u sakshigawande12:c08e2159331343703c2f6581840d2871cbd53ca9 \
  https://api.github.com/orgs/knoldus-test/actions/secrets/DOCKERHUB_USERNAME

Here I passed the secret the “DOCKERHUB_USERNAME“.

Response:

{
  "name": "DOCKERHUB_USERNAME",
  "created_at": "2021-03-26T07:24:33Z",
  "updated_at": "2021-03-26T07:24:33Z",
  "visibility": "all"
}

4. Create or Update an organization secret

Creates or updates an organization’s secret with an encrypted value. Encrypt your secret using LibSodium. (To know about the LibSodium click on the Blue LibSodium). You must authenticate using an access token with the admin:org scope to use this endpoint.

Example of encrypting a secret using Node.js

const sodium = require('tweetsodium');

const key = "base64-encoded-public-key";
const value = "plain-text-secret";

// Convert the message and key to Uint8Array's (Buffer implements that interface)
const messageBytes = Buffer.from(value);
const keyBytes = Buffer.from(key, 'base64');

// Encrypt using LibSodium.
const encryptedBytes = sodium.seal(messageBytes, keyBytes);

// Base64 the encrypted secret
const encrypted = Buffer.from(encryptedBytes).toString('base64');

console.log(encrypted);

So using the above code we can encrypt the value for our secret. And then create or update the secret.

But before executing the above code get the public key using the second operation. Then put the value at the place of “base64-encoded-public-key

PUT /orgs/{org}/actions/secrets/{secret_name}

Example:

curl \
  -X PUT \
  -H "Accept: application/vnd.github.v3+json" \
  -u sakshigawande:c08e2159331343703c2f6581840d2871cbd53ca9 \
  https://api.github.com/orgs/knoldus-test/actions/secrets/CREATED_SECRET \
  -d '{"encrypted_value":"xNictGdgDsBmGIzHoEknu5yWf366h5RTNdSFF5eCD37kXryPmLrTjk2nOTOQQQF24K4ep1gt7jFsFCY+aU6o5Q==", "key_id": "568250167242549743","visibility":"all"}'

I passed the secret name as “CREATED_SECRET“. You can pass whatever name you want. One more thing you need to pass the visibility as well with key encrypted_value and key_id.

If the Secret passed with the name you provided is already present at the organization level. Then it’ll get updated with the new value. Otherwise, the new secret gets created.

The more parameter you can pass:

NameTypeInDescription
acceptstringheaderSetting to application/vnd.github.v3+json is recommended.
orgstringpath 
secret_namestringpathsecret_name parameter
encrypted_valuestringbodyValue for your secret.Encrypted with LibSodium using the public key retrieved from the Get an organization public key endpoint.
key_idstringbodyID of the key you used to encrypt the secret.
visibilitystringbodyConfigures the access that repositories have to the organization secret. Can be one of: all – All repositories in an organization can access the secret. private – Private repositories in an organization can access the secret. selected – Only specific repositories can access the secret.
selected_repository_idsarray of stringbodyAn array of repository ids that can access the organization secret. You can only provide a list of repository ids. When the visibility is set to selected. You can manage the list of selected repositories. Using the List selected repositories for an organization secret. Similarly Set selected repositories for an organization secret. And Remove selected repository from an organization secret endpoints.

Response: when creating a secret

Status: 201 Created

Response: when updating a secret

Status: 204 No Content

5. Delete an organization secret

Deletes a secret in an organization using the secret name. You must authenticate using an access token with the admin:org scope to use this endpoint

1delete /orgs/{org}/actions/secrets/{secret_name}

Parameters:

NameTypeInDescription
acceptstringheaderSetting to application/vnd.github.v3+json is recommended.
orgstringpath 
secret_namestringpathsecret_name parameter

Example:

curl \
  -X DELETE \
  -H "Accept: application/vnd.github.v3+json" \
  https://api.github.com/orgs/knoldus-test/actions/secrets/CREATED_SECRET

The “CREATED_SECRET” gets deleted.

Response:

Status: 204 No Content

6. List selected repositories for an organization secret

Lists all repositories that have been selected when the visibility for repository access to a secret is set to selected. You must authenticate using an access token with the admin:org scope to use this endpoint.

get /orgs/{org}/actions/secrets/{secret_name}/repositories

Parameters:

NameTypeInDescription
acceptstringheaderSetting to application/vnd.github.v3+json is recommended.
orgstringpath 
secret_namestringpathsecret_name parameter
pageintegerqueryPage number of the results to fetch.
per_pageintegerqueryResults per page (max 100).

Example:

curl \
  -H "Accept: application/vnd.github.v3+json" \
  https://api.github.com/orgs/knoldus-test/actions/secrets/DOCKERHUB_USERNAME/repositories

Response:

{
  "total_count": 1,
  "repositories": [
    {
      "id": 1296269,
      "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5",
      "name": "Hello-World",
      "full_name": "octocat/Hello-World",
      "owner": {
        "login": "octocat",
        "id": 1,
        "node_id": "MDQ6VXNlcjE=",
        "avatar_url": "https://github.com/images/error/octocat_happy.gif",
        "gravatar_id": "",
        "url": "https://api.github.com/users/octocat",
        "html_url": "https://github.com/octocat",
        "followers_url": "https://api.github.com/users/octocat/followers",
        "following_url": "https://api.github.com/users/octocat/following{/other_user}",
        "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",
        "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",
        "subscriptions_url": "https://api.github.com/users/octocat/subscriptions",
        "organizations_url": "https://api.github.com/users/octocat/orgs",
        "repos_url": "https://api.github.com/users/octocat/repos",
        "events_url": "https://api.github.com/users/octocat/events{/privacy}",
        "received_events_url": "https://api.github.com/users/octocat/received_events",
        "type": "User",
        "site_admin": false
      },
      "private": false,
      "html_url": "https://github.com/octocat/Hello-World",
      "description": "This your first repo!",
      "fork": false,
      "url": "https://api.github.com/repos/octocat/Hello-World",
      "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}",
      "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}",
      "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}",
      "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}",
      "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}",
      "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}",
      "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}",
      "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}",
      "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}",
      "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors",
      "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments",
      "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads",
      "events_url": "https://api.github.com/repos/octocat/Hello-World/events",
      "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks",
      "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}",
      "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}",
      "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}",
      "git_url": "git:github.com/octocat/Hello-World.git",
      "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}",
      "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}",
      "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}",
      "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}",
      "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}",
      "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages",
      "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges",
      "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}",
      "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}",
      "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}",
      "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}",
      "ssh_url": "git@github.com:octocat/Hello-World.git",
      "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers",
      "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}",
      "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers",
      "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription",
      "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags",
      "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams",
      "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}",
      "hooks_url": "http://api.github.com/repos/octocat/Hello-World/hooks"
    }
  ]
}

7. Set selected repositories for an organization secret

Replaces all repositories for an organization secret when the visibility for repository access is set to selected. The visibility is set when you create or update an organization’s secret. You must authenticate using an access token with the admin:org scope to use this endpoint.

PUT /orgs/{org}/actions/secrets/{secret_name}/repositories

Parameters:

NameTypeInDescription
acceptstringheaderSetting to application/vnd.github.v3+json is recommended.
orgstringpath 
secret_namestringpathsecret_name parameter
selected_repository_idsarray of integersbodyAn array of repository ids that can access the organization secret. You can only provide a list of repository ids when the visibility is set to selected. You can add and remove individual repositories using the Set selected repositories for an organization secret and Remove selected repository from an organization secret endpoints.

Example:

curl \
  -X PUT \
  -H "Accept: application/vnd.github.v3+json" \
  https://api.github.com/orgs/knoldus-test/actions/secrets/DOCKERHUB_USERNAME/repositories \
  -d '{"selected_repository_ids":[42]}'

Response:

Status: 204 No Content

8. Add a selected repository to an organization secret

Adds a repository to an organization secret when the visibility for repository access is set to selected. The visibility is set when you create or update an organization’s secret. You must authenticate using an access token with the admin:org scope to use this endpoint.

PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}

Parameters:

NameTypeInDescription
acceptstringheaderSetting to application/vnd.github.v3+json is recommended.
orgstringpath 
secret_namestringpathsecret_name parameter
repository_idintegerpath 

Example:

curl \
  -X PUT \
  -H "Accept: application/vnd.github.v3+json" \
  https://api.github.com/orgs/ORG/actions/secrets/SECRET_NAME/repositories/42

Response: when repository was added to the selected list

Status: 204 No Content

Response when visibility type is not set to selected

Status: 409 Conflict

9. Remove a selected repository to an organization secret

Removes a repository from an organization secret when the visibility for repository access is set to selected. You must authenticate using an access token with the admin:org scope to use this endpoint.

1DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}

Parameters:

NameTypeInDescription
acceptstringheaderSetting to application/vnd.github.v3+json is recommended.
orgstringpath 
secret_namestringpathsecret_name parameter
repository_idintegerpath 

Example:

curl \
  -X DELETE \
  -H "Accept: application/vnd.github.v3+json" \
  https://api.github.com/orgs/ORG/actions/secrets/SECRET_NAME/repositories/42

Response: when the repository was removed from the selected list

Status: 204 No Content

Response: when visibility type not selected

Status: 409 Conflict

Now, we’ll see the different operations perform using GitHub Secret API at the repository level.

Consider the repo “HelloWorld” with the owner “sakshigawande12“

1. List repo secrets

lt ists all secrets available in a repository without revealing their encrypted values. You must authenticate using an access token with the repo scope to use this endpoint.

get /repos/{owner}/{repo}/actions/secrets

Parameters:

NameTypeInDescription
acceptstringheaderSetting to application/vnd.github.v3+json is recommended.
ownerstringpath 
repostringpath 
pageintegerqueryPage number of the results to fetch.
per_pageintegerqueryResults per page (max 100).

Example:

curl -H "Accept: application/vnd.github.v3+json" \
-H "Authorization: token 6b492fb74dca707179b5c1ed096c67edbf7ac532" \
https://api.github.com/repos/sakshigawande12/HelloWorld/actions/secrets

Response:

{
  "total_count": 4,
  "secrets": [
    {
      "name": "ACCESS_TOKEN",
      "created_at": "2021-01-08T12:54:08Z",
      "updated_at": "2021-01-08T12:54:08Z"
    },
    {
      "name": "DOCKERHUB_PASSWORD",
      "created_at": "2021-03-14T07:37:43Z",
      "updated_at": "2021-03-14T07:37:43Z"
    },
    {
      "name": "DOCKERHUB_USERNAME",
      "created_at": "2021-03-14T07:37:02Z",
      "updated_at": "2021-03-14T07:37:02Z"
    },
    {
      "name": "SECRET_NAME",
      "created_at": "2021-03-25T06:02:06Z",
      "updated_at": "2021-03-25T06:06:47Z"
    }
  ]
}

2. Get a repository public key

Gets your public key, which you need to encrypt secrets. Anyone with reading access to the repository can use this endpoint. If the repository is private you must use an access token with the repo scope. For public repo you don’t need a PAT.

GET /repos/{owner}/{repo}/actions/secrets/public-key

Parameters:

NameTypeInDescription
acceptstringheaderSetting to application/vnd.github.v3+json is recommended.
ownerstringpath 
repostringpath 

Example:

curl \
  -H "Accept: application/vnd.github.v3+json" \
  -u sakshigawande12:6b492fb74dca707179b5c1ed096c67edbf7ac532 \
  https://api.github.com/repos/sakshigawande12/HelloWorld/actions/secrets/public-key

Response:

{
  "key_id": "568250167242549743",
  "key": "ZVP3GLWhZY1LQiP17LcowpikJ6zIPKbQbd4v50bDaT0="
}

3. Get a repository secret

Gets a single repository secret without revealing its encrypted value. You must authenticate using an access token with the repo scope to use this endpoint.

GET /repos/{owner}/{repo}/actions/secrets/{secret_name}

Parameters:

NameTypeInDescription
acceptstringheaderSetting to application/vnd.github.v3+json is recommended.
ownerstringpath 
repostringpath 
secret_namestringpathsecret_name parameter

Example:

curl -H "Accept: application/vnd.github.v3+json" \
-H "Authorization: token 6b492fb74dca707179b5c1ed096c67edbf7ac532" \
https://api.github.com/repos/sakshigawande12/HelloWorld/actions/secrets/ACCESS_TOKEN

Response:

{
  "name": "ACCESS_TOKEN",
  "created_at": "2021-01-08T12:54:08Z",
  "updated_at": "2021-01-08T12:54:08Z"
}

4. Create/Update repository secret

Creates or updates a repository secret with an encrypted value. Encrypt your secret using LibSodium. You must authenticate using an access token with the repo scope to use this endpoint

Example encrypting a secret using Node.js

const sodium = require('tweetsodium');

const key = "base64-encoded-public-key";
const value = "plain-text-secret";

// Convert the message and key to Uint8Array's (Buffer implements that interface)
const messageBytes = Buffer.from(value);
const keyBytes = Buffer.from(key, 'base64');

// Encrypt using LibSodium.
const encryptedBytes = sodium.seal(messageBytes, keyBytes);

// Base64 the encrypted secret
const encrypted = Buffer.from(encryptedBytes).toString('base64');

console.log(encrypted);

However utilizing the above code we can encrypt the value for our secret. However utilizing this encryted value you can engender or update the secret that you want.

But before executing the above code, get the public key using the second operation. Then put the value at the place of “base64-encoded-public-key

Then use the following API.

put /repos/{owner}/{repo}/actions/secrets/{secret_name}

Parameters:

NameTypeInDescription
acceptstringheaderSetting to application/vnd.github.v3+json is recommended.
ownerstringpath 
repostringpath 
secret_namestringpathsecret_name parameter
encrypted_valuestringbodyValue for your secret. Encrypted with LibSodium using the public key retrieved from the Get a repository public key endpoint.
key_idstringbodyID of the key you used to encrypt the secret.

Example:

curl   -X PUT   -H "Accept: application/vnd.github.v3+json" \
  -u sakshigawande12:6b492fb74dca707179b5c1ed096c67edbf7ac532 \
  https://api.github.com/repos/sakshigawande12/HelloWorld/actions/secrets/SECRET_NAME \
  -d '{"encrypted_value":"1DJ3ciJgF6gIqRGLBMJH40mpccqBh25PDzOt3CfWi3JRALW8t1r3nqyJKIfK1qqMekstC3iK7Ze9ncw3vcHQJg==","key_id": "568250167242549743"}

Response: when creating the secret

Status: 201 Created

Response: when updating the secret

Status: 204 No Content

5. Delete a repository secret

Deletes a secret in a repository using the secret name. You must authenticate using an access token with the repo scope to use this endpoint.

DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}

Parameters:

NameTypeInDescription
NameTypeInDescription
acceptstringheaderSetting to application/vnd.github.v3+json is recommended.
ownerstringpath 
repostringpath 
secret_namestringpathsecret_name parameter
1Status: 204 No Content

Example:

curl \
  -X DELETE \
  -H "Accept: application/vnd.github.v3+json" \
  -H "Authorization: token 6b492fb74dca707179b5c1ed096c67edbf7ac532 \
  https://api.github.com/repos/sakshigawande12/HelloWorld/actions/secrets/ACCESS_TOKEN

Response:

Status: 204 No Content

Note : Here are some other blogs that you can refer to know about GitHub actions

https://blog.knoldus.com/ci-cd-using-github-actions/
https://blog.knoldus.com/manual-trigger-in-github-actions/

References:

https://docs.github.com/en/rest/reference/actions

Written by 

Sakshi Gawande is a software consultant at "KNOLDUS" having more than 2 years of experience. She's working as a DevOps engineer. She always wants to explore new things and solve problems herself. on personal, she likes dancing, painting, and traveling.

Leave a Reply