Skip to content

Commit

Permalink
Add support for GitHub secrets.
Browse files Browse the repository at this point in the history
Adds support for organization and repository
secrets. As these are part of the Actions API
they are put into a new submodule
github3.actions.
Currently support OrganizationSecrets and
RepositorySecrets.

more info on the API at
https://developer.github.com/v3/actions/secrets
  • Loading branch information
MrBatschner committed Jun 21, 2023
1 parent 43aa2d6 commit 51a7151
Show file tree
Hide file tree
Showing 24 changed files with 6,658 additions and 0 deletions.
2 changes: 2 additions & 0 deletions AUTHORS.rst
Expand Up @@ -222,3 +222,5 @@ Contributors
- Andrew MacCormack (@amaccormack-lumira)

- Chris R (@offbyone)

- Thomas Buchner (@MrBatschner)
20 changes: 20 additions & 0 deletions src/github3/actions/__init__.py
@@ -0,0 +1,20 @@
"""
github3.actions
=============
Module which contains all GitHub Actions related material (only secrets
so far).
See also: http://developer.github.com/v3/actions/
"""
from .secrets import (
OrganizationSecret,
RepositorySecret,
SharedOrganizationSecret,
)

__all__ = (
"OrganizationSecret",
"RepositorySecret",
"SharedOrganizationSecret",
)
228 changes: 228 additions & 0 deletions src/github3/actions/secrets.py
@@ -0,0 +1,228 @@
"""This module contains all the classes relating to GitHub Actions secrets."""

import typing

from .. import models


class PublicKey(models.GitHubCore):

"""Object representing a Public Key for GitHub Actions secrets.
See https://docs.github.com/en/rest/actions/secrets for more details.
.. attribute:: key_id
The ID of the public key
.. attribute:: key
The actual public key as a string
"""

def _update_attributes(self, publickey):
self.key_id = publickey["key_id"]
self.key = publickey["key"]

def _repr(self):
return f"<PublicKey [{self.key_id}]>"

def __str__(self):
return self.key


class _Secret(models.GitHubCore):

"""Base class for all secrets for GitHub Actions.
See https://docs.github.com/en/rest/actions/secrets for more details.
GitHub never reveals the secret value through its API, it is only accessible
from within actions. Therefore, this object represents the secret's metadata
but not its actual value.
"""

class_name = "_Secret"

def _repr(self):
return f"<{self.class_name} [{self.name}]>"

def __str__(self):
return self.name

def _update_attributes(self, secret):
self.name = secret["name"]
self.created_at = self._strptime(secret["created_at"])
self.updated_at = self._strptime(secret["updated_at"])


class RepositorySecret(_Secret):
"""An object representing a repository secret for GitHub Actions.
See https://docs.github.com/en/rest/actions/secrets for more details.
GitHub never reveals the secret value through its API, it is only accessible
from within actions. Therefore, this object represents the secret's metadata
but not its actual value.
.. attribute:: name
The name of the secret
.. attribute:: created_at
The timestamp of when the secret was created
.. attribute:: updated_at
The timestamp of when the secret was last updated
"""

class_name = "RepositorySecret"


class SharedOrganizationSecret(_Secret):
"""An object representing an organization secret for GitHub Actions that is
shared with the repository.
See https://docs.github.com/en/rest/actions/secrets for more details.
GitHub never reveals the secret value through its API, it is only accessible
from within actions. Therefore, this object represents the secret's metadata
but not its actual value.
.. attribute:: name
The name of the secret
.. attribute:: created_at
The timestamp of when the secret was created
.. attribute:: updated_at
The timestamp of when the secret was last updated
"""

class_name = "SharedOrganizationSecret"


class OrganizationSecret(_Secret):
"""An object representing am organization secret for GitHub Actions.
See https://docs.github.com/en/rest/actions/secrets for more details.
GitHub never reveals the secret value through its API, it is only accessible
from within actions. Therefore, this object represents the secret's metadata
but not its actual value.
.. attribute:: name
The name of the secret
.. attribute:: created_at
The timestamp of when the secret was created
.. attribute:: updated_at
The timestamp of when the secret was last updated
"""

class_name = "OrganizationSecret"

def _update_attributes(self, secret):
super()._update_attributes(secret)
self.visibility = secret["visibility"]
if self.visibility == "selected":
self._selected_repos_url = secret["selected_repositories_url"]

def selected_repositories(self, number=-1, etag=""):
"""Iterates over all repositories this secret is visible to.
:param int number:
(optional), number of repositories to return.
Default: -1 returns all selected repositories.
:param str etag:
(optional), ETag from a previous request to the same endpoint
:returns:
Generator of selected repositories or None if the visibility of this
secret is not set to 'selected'.
:rtype:
:class:`~github3.repos.ShortRepository`
"""
from .. import repos

if self.visibility != "selected":
return None

return self._iter(
int(number),
self._selected_repos_url,
repos.ShortRepository,
etag=etag,
list_key="repositories",
)

def set_selected_repositories(self, repository_ids: typing.List[int]):
"""Sets the selected repositories this secret is visible to.
:param list[int] repository_ids:
A list of repository IDs which this secret should be visible to.
:returns:
A boolean indicating whether the update was successful.
:rtype:
bool
"""
if self.visibility != "selected":
raise ValueError(
"""cannot set a list of selected repositories when visibility
is not 'selected'"""
)

data = {"selected_repository_ids": repository_ids}

return self._boolean(
self._put(self._selected_repos_url, json=data), 204, 404
)

def add_selected_repository(self, repository_id: int):
"""Adds a repository to the list of repositories this secret is
visible to.
:param int repository_id:
The IDs of a repository this secret should be visible to.
:raises:
A ValueError if the visibility of this secret is not 'selected'.
:returns:
A boolean indicating if the repository was successfully added to
the visible list.
:rtype:
bool
"""
if self.visibility != "selected":
raise ValueError(
"cannot add a repository when visibility is not 'selected'"
)

url = "/".join([self._selected_repos_url, str(repository_id)])
return self._boolean(self._put(url), 204, 409)

def delete_selected_repository(self, repository_id: int):
"""Deletes a repository from the list of repositories this secret is
visible to.
:param int repository_id:
The IDs of the repository this secret should no longer be
visible to.
:raises:
A ValueError if the visibility of this secret is not 'selected'.
:returns:
A boolean indicating if the repository was successfully removed
from the visible list.
:rtype:
bool
"""
if self.visibility != "selected":
raise ValueError(
"cannot delete a repository when visibility is not 'selected'"
)

url = "/".join([self._selected_repos_url, str(repository_id)])
return self._boolean(self._delete(url), 204, 409)
129 changes: 129 additions & 0 deletions src/github3/orgs.py
Expand Up @@ -11,6 +11,8 @@
from .projects import Project
from .repos import Repository
from .repos import ShortRepository
from . import exceptions
from .actions import secrets as actionsecrets

if t.TYPE_CHECKING:
from . import users as _users
Expand Down Expand Up @@ -1276,6 +1278,133 @@ def team_by_name(self, team_slug: str) -> t.Optional[Team]:
json = self._json(self._get(url), 200)
return self._instance_or_null(Team, json)

@requires_auth
def public_key(self) -> t.Optional[actionsecrets.PublicKey]:
"""Retrieves an organizations public-key for GitHub Actions secrets
:returns:
the public key of the organization
:rtype:
:class:`~github3.secrets.PublicKey`
"""
url = self._build_url(
"orgs", self.login, "actions", "secrets", "public-key"
)
json = self._json(self._get(url), 200)
return self._instance_or_null(actionsecrets.PublicKey, json)

@requires_auth
def secrets(self, number=-1, etag=None):
"""Iterate over all GitHub Actions secrets of an organization.
:param int number:
(optional), number of secrets to return.
Default: -1 returns all available secrets
:param str etag:
(optional), ETag from a previous request to the same endpoint
:returns:
Generator of organization secrets.
:rtype:
:class:`~github3.secrets.OrganizationSecret`
"""
url = self._build_url("orgs", self.login, "actions", "secrets")
return self._iter(
int(number),
url,
actionsecrets.OrganizationSecret,
etag=etag,
list_key="secrets",
)

@requires_auth
def secret(self, secret_name):
"""Returns the organization secret with the given name.
:param str secret_name:
Name of the organization secret to obtain.
:returns:
The organization secret with the given name.
:rtype:
:class:`~github3.secrets.OrganizationSecret`
"""
url = self._build_url(
"orgs", self.login, "actions", "secrets", secret_name
)
json = self._json(self._get(url), 200)
return self._instance_or_null(actionsecrets.OrganizationSecret, json)

@requires_auth
def create_or_update_secret(
self, secret_name, encrypted_value, visibility, selected_repo_ids=None
):
"""Creates or updates an organization secret.
:param str secret_name:
Name of the organization secret to be created or updated.
:param str encrypted_value:
The value of the secret which was previously encrypted
by the organizations public key.
Check
https://developer.github.com/v3/actions/secrets#create-or-update-an-organization-secret
for how to properly encrypt the secret value before using
this function.
:param str visibility:
Visibility of this organization secret, must be one of 'all',
'private' or 'selected'.
:param list[int] selected_repo_ids:
A list of repository IDs this secret should be visible to, required
if visibility is 'selected'.
:returns:
The secret that was just created or updated.
:rtype:
:class:`~github3.py.secrets.OrganizationSecret`
"""
data = {}

if visibility not in ("all", "private", "selected"):
raise ValueError(
"visibility must be 'all', 'private' or 'selected'"
)
data.update(visibility=visibility)

if visibility == "selected":
if selected_repo_ids is None or len(selected_repo_ids) == 0:
raise ValueError(
"must supply a list of repos IDs for visibility 'selected'"
)
else:
data.update(selected_repository_ids=selected_repo_ids)

data.update(encrypted_value=encrypted_value)
data.update(key_id=self.public_key().key_id)

url = self._build_url(
"orgs", self.login, "actions", "secrets", secret_name
)
response = self._put(url, json=data)
if response.status_code not in (201, 204):
raise exceptions.error_for(response)

# PUT for secrets does not return anything but having a secret
# object at least containing the timestamps would be nice
return self.secret(secret_name)

@requires_auth
def delete_secret(self, secret_name):
"""Deletes an organization secret.
:param str secret_name:
The name of the secret to delete.
:returns:
A boolean indicating whether the secret was successfully deleted.
:rtype:
bool
"""
url = self._build_url(
"orgs", self.login, "actions", "secrets", secret_name
)
return self._boolean(self._delete(url), 204, 404)


class Organization(_Organization):
"""Object for the full representation of a Organization.
Expand Down

0 comments on commit 51a7151

Please sign in to comment.