Skip to content

Commit 117dafc

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 c6b5017 commit 117dafc

24 files changed

+6656
-0
lines changed

Diff for: 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)

Diff for: 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+
)

Diff for: src/github3/actions/secrets.py

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

Diff for: 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)