Skip to content

Commit 51a7151

Browse files
committed
Add support for GitHub secrets.
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
1 parent 43aa2d6 commit 51a7151

24 files changed

+6658
-0
lines changed

AUTHORS.rst

+2
Original file line numberDiff line numberDiff line change
@@ -222,3 +222,5 @@ Contributors
222222
- Andrew MacCormack (@amaccormack-lumira)
223223

224224
- Chris R (@offbyone)
225+
226+
- Thomas Buchner (@MrBatschner)

src/github3/actions/__init__.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
"""
2+
github3.actions
3+
=============
4+
5+
Module which contains all GitHub Actions related material (only secrets
6+
so far).
7+
8+
See also: http://developer.github.com/v3/actions/
9+
"""
10+
from .secrets import (
11+
OrganizationSecret,
12+
RepositorySecret,
13+
SharedOrganizationSecret,
14+
)
15+
16+
__all__ = (
17+
"OrganizationSecret",
18+
"RepositorySecret",
19+
"SharedOrganizationSecret",
20+
)

src/github3/actions/secrets.py

+228
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,228 @@
1+
"""This module contains all the classes relating to GitHub Actions secrets."""
2+
3+
import typing
4+
5+
from .. import models
6+
7+
8+
class PublicKey(models.GitHubCore):
9+
10+
"""Object representing a Public Key for GitHub Actions secrets.
11+
12+
See https://docs.github.com/en/rest/actions/secrets for more details.
13+
14+
.. attribute:: key_id
15+
16+
The ID of the public key
17+
18+
.. attribute:: key
19+
20+
The actual public key as a string
21+
"""
22+
23+
def _update_attributes(self, publickey):
24+
self.key_id = publickey["key_id"]
25+
self.key = publickey["key"]
26+
27+
def _repr(self):
28+
return f"<PublicKey [{self.key_id}]>"
29+
30+
def __str__(self):
31+
return self.key
32+
33+
34+
class _Secret(models.GitHubCore):
35+
36+
"""Base class for all secrets for GitHub Actions.
37+
38+
See https://docs.github.com/en/rest/actions/secrets for more details.
39+
GitHub never reveals the secret value through its API, it is only accessible
40+
from within actions. Therefore, this object represents the secret's metadata
41+
but not its actual value.
42+
"""
43+
44+
class_name = "_Secret"
45+
46+
def _repr(self):
47+
return f"<{self.class_name} [{self.name}]>"
48+
49+
def __str__(self):
50+
return self.name
51+
52+
def _update_attributes(self, secret):
53+
self.name = secret["name"]
54+
self.created_at = self._strptime(secret["created_at"])
55+
self.updated_at = self._strptime(secret["updated_at"])
56+
57+
58+
class RepositorySecret(_Secret):
59+
"""An object representing a repository secret for GitHub Actions.
60+
61+
See https://docs.github.com/en/rest/actions/secrets for more details.
62+
GitHub never reveals the secret value through its API, it is only accessible
63+
from within actions. Therefore, this object represents the secret's metadata
64+
but not its actual value.
65+
66+
.. attribute:: name
67+
68+
The name of the secret
69+
70+
.. attribute:: created_at
71+
72+
The timestamp of when the secret was created
73+
74+
.. attribute:: updated_at
75+
76+
The timestamp of when the secret was last updated
77+
"""
78+
79+
class_name = "RepositorySecret"
80+
81+
82+
class SharedOrganizationSecret(_Secret):
83+
"""An object representing an organization secret for GitHub Actions that is
84+
shared with the repository.
85+
86+
See https://docs.github.com/en/rest/actions/secrets for more details.
87+
GitHub never reveals the secret value through its API, it is only accessible
88+
from within actions. Therefore, this object represents the secret's metadata
89+
but not its actual value.
90+
91+
.. attribute:: name
92+
93+
The name of the secret
94+
95+
.. attribute:: created_at
96+
97+
The timestamp of when the secret was created
98+
99+
.. attribute:: updated_at
100+
101+
The timestamp of when the secret was last updated
102+
"""
103+
104+
class_name = "SharedOrganizationSecret"
105+
106+
107+
class OrganizationSecret(_Secret):
108+
"""An object representing am organization secret for GitHub Actions.
109+
110+
See https://docs.github.com/en/rest/actions/secrets for more details.
111+
GitHub never reveals the secret value through its API, it is only accessible
112+
from within actions. Therefore, this object represents the secret's metadata
113+
but not its actual value.
114+
115+
.. attribute:: name
116+
117+
The name of the secret
118+
119+
.. attribute:: created_at
120+
121+
The timestamp of when the secret was created
122+
123+
.. attribute:: updated_at
124+
125+
The timestamp of when the secret was last updated
126+
"""
127+
128+
class_name = "OrganizationSecret"
129+
130+
def _update_attributes(self, secret):
131+
super()._update_attributes(secret)
132+
self.visibility = secret["visibility"]
133+
if self.visibility == "selected":
134+
self._selected_repos_url = secret["selected_repositories_url"]
135+
136+
def selected_repositories(self, number=-1, etag=""):
137+
"""Iterates over all repositories this secret is visible to.
138+
139+
:param int number:
140+
(optional), number of repositories to return.
141+
Default: -1 returns all selected repositories.
142+
:param str etag:
143+
(optional), ETag from a previous request to the same endpoint
144+
:returns:
145+
Generator of selected repositories or None if the visibility of this
146+
secret is not set to 'selected'.
147+
:rtype:
148+
:class:`~github3.repos.ShortRepository`
149+
"""
150+
from .. import repos
151+
152+
if self.visibility != "selected":
153+
return None
154+
155+
return self._iter(
156+
int(number),
157+
self._selected_repos_url,
158+
repos.ShortRepository,
159+
etag=etag,
160+
list_key="repositories",
161+
)
162+
163+
def set_selected_repositories(self, repository_ids: typing.List[int]):
164+
"""Sets the selected repositories this secret is visible to.
165+
166+
:param list[int] repository_ids:
167+
A list of repository IDs which this secret should be visible to.
168+
:returns:
169+
A boolean indicating whether the update was successful.
170+
:rtype:
171+
bool
172+
"""
173+
if self.visibility != "selected":
174+
raise ValueError(
175+
"""cannot set a list of selected repositories when visibility
176+
is not 'selected'"""
177+
)
178+
179+
data = {"selected_repository_ids": repository_ids}
180+
181+
return self._boolean(
182+
self._put(self._selected_repos_url, json=data), 204, 404
183+
)
184+
185+
def add_selected_repository(self, repository_id: int):
186+
"""Adds a repository to the list of repositories this secret is
187+
visible to.
188+
189+
:param int repository_id:
190+
The IDs of a repository this secret should be visible to.
191+
:raises:
192+
A ValueError if the visibility of this secret is not 'selected'.
193+
:returns:
194+
A boolean indicating if the repository was successfully added to
195+
the visible list.
196+
:rtype:
197+
bool
198+
"""
199+
if self.visibility != "selected":
200+
raise ValueError(
201+
"cannot add a repository when visibility is not 'selected'"
202+
)
203+
204+
url = "/".join([self._selected_repos_url, str(repository_id)])
205+
return self._boolean(self._put(url), 204, 409)
206+
207+
def delete_selected_repository(self, repository_id: int):
208+
"""Deletes a repository from the list of repositories this secret is
209+
visible to.
210+
211+
:param int repository_id:
212+
The IDs of the repository this secret should no longer be
213+
visible to.
214+
:raises:
215+
A ValueError if the visibility of this secret is not 'selected'.
216+
:returns:
217+
A boolean indicating if the repository was successfully removed
218+
from the visible list.
219+
:rtype:
220+
bool
221+
"""
222+
if self.visibility != "selected":
223+
raise ValueError(
224+
"cannot delete a repository when visibility is not 'selected'"
225+
)
226+
227+
url = "/".join([self._selected_repos_url, str(repository_id)])
228+
return self._boolean(self._delete(url), 204, 409)

src/github3/orgs.py

+129
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
from .projects import Project
1212
from .repos import Repository
1313
from .repos import ShortRepository
14+
from . import exceptions
15+
from .actions import secrets as actionsecrets
1416

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

1281+
@requires_auth
1282+
def public_key(self) -> t.Optional[actionsecrets.PublicKey]:
1283+
"""Retrieves an organizations public-key for GitHub Actions secrets
1284+
1285+
:returns:
1286+
the public key of the organization
1287+
:rtype:
1288+
:class:`~github3.secrets.PublicKey`
1289+
"""
1290+
url = self._build_url(
1291+
"orgs", self.login, "actions", "secrets", "public-key"
1292+
)
1293+
json = self._json(self._get(url), 200)
1294+
return self._instance_or_null(actionsecrets.PublicKey, json)
1295+
1296+
@requires_auth
1297+
def secrets(self, number=-1, etag=None):
1298+
"""Iterate over all GitHub Actions secrets of an organization.
1299+
1300+
:param int number:
1301+
(optional), number of secrets to return.
1302+
Default: -1 returns all available secrets
1303+
:param str etag:
1304+
(optional), ETag from a previous request to the same endpoint
1305+
:returns:
1306+
Generator of organization secrets.
1307+
:rtype:
1308+
:class:`~github3.secrets.OrganizationSecret`
1309+
"""
1310+
url = self._build_url("orgs", self.login, "actions", "secrets")
1311+
return self._iter(
1312+
int(number),
1313+
url,
1314+
actionsecrets.OrganizationSecret,
1315+
etag=etag,
1316+
list_key="secrets",
1317+
)
1318+
1319+
@requires_auth
1320+
def secret(self, secret_name):
1321+
"""Returns the organization secret with the given name.
1322+
1323+
:param str secret_name:
1324+
Name of the organization secret to obtain.
1325+
:returns:
1326+
The organization secret with the given name.
1327+
:rtype:
1328+
:class:`~github3.secrets.OrganizationSecret`
1329+
"""
1330+
url = self._build_url(
1331+
"orgs", self.login, "actions", "secrets", secret_name
1332+
)
1333+
json = self._json(self._get(url), 200)
1334+
return self._instance_or_null(actionsecrets.OrganizationSecret, json)
1335+
1336+
@requires_auth
1337+
def create_or_update_secret(
1338+
self, secret_name, encrypted_value, visibility, selected_repo_ids=None
1339+
):
1340+
"""Creates or updates an organization secret.
1341+
1342+
:param str secret_name:
1343+
Name of the organization secret to be created or updated.
1344+
:param str encrypted_value:
1345+
The value of the secret which was previously encrypted
1346+
by the organizations public key.
1347+
Check
1348+
https://developer.github.com/v3/actions/secrets#create-or-update-an-organization-secret
1349+
for how to properly encrypt the secret value before using
1350+
this function.
1351+
:param str visibility:
1352+
Visibility of this organization secret, must be one of 'all',
1353+
'private' or 'selected'.
1354+
:param list[int] selected_repo_ids:
1355+
A list of repository IDs this secret should be visible to, required
1356+
if visibility is 'selected'.
1357+
:returns:
1358+
The secret that was just created or updated.
1359+
:rtype:
1360+
:class:`~github3.py.secrets.OrganizationSecret`
1361+
"""
1362+
data = {}
1363+
1364+
if visibility not in ("all", "private", "selected"):
1365+
raise ValueError(
1366+
"visibility must be 'all', 'private' or 'selected'"
1367+
)
1368+
data.update(visibility=visibility)
1369+
1370+
if visibility == "selected":
1371+
if selected_repo_ids is None or len(selected_repo_ids) == 0:
1372+
raise ValueError(
1373+
"must supply a list of repos IDs for visibility 'selected'"
1374+
)
1375+
else:
1376+
data.update(selected_repository_ids=selected_repo_ids)
1377+
1378+
data.update(encrypted_value=encrypted_value)
1379+
data.update(key_id=self.public_key().key_id)
1380+
1381+
url = self._build_url(
1382+
"orgs", self.login, "actions", "secrets", secret_name
1383+
)
1384+
response = self._put(url, json=data)
1385+
if response.status_code not in (201, 204):
1386+
raise exceptions.error_for(response)
1387+
1388+
# PUT for secrets does not return anything but having a secret
1389+
# object at least containing the timestamps would be nice
1390+
return self.secret(secret_name)
1391+
1392+
@requires_auth
1393+
def delete_secret(self, secret_name):
1394+
"""Deletes an organization secret.
1395+
1396+
:param str secret_name:
1397+
The name of the secret to delete.
1398+
:returns:
1399+
A boolean indicating whether the secret was successfully deleted.
1400+
:rtype:
1401+
bool
1402+
"""
1403+
url = self._build_url(
1404+
"orgs", self.login, "actions", "secrets", secret_name
1405+
)
1406+
return self._boolean(self._delete(url), 204, 404)
1407+
12791408

12801409
class Organization(_Organization):
12811410
"""Object for the full representation of a Organization.

0 commit comments

Comments
 (0)