-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgithub.py
64 lines (50 loc) · 1.81 KB
/
github.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
from os import environ
from base64 import b64encode
import logging
from typing import NoReturn
import requests
from nacl import encoding, public
def encrypt(public_key, secret_value) -> str:
"""
Encrypt a Unicode string using the public key.
:param public_key: The public key to use for encryption.
:param secret_value: The secret value to encrypt.
:return: The encrypted secret value.
"""
public_key = public.PublicKey(public_key.encode("utf-8"), encoding.Base64Encoder)
sealed_box = public.SealedBox(public_key)
encrypted = sealed_box.encrypt(secret_value.encode("utf-8"))
return b64encode(encrypted).decode("utf-8")
def get_pub_key(repos: str, token: str) -> tuple[str, int]:
url = 'https://api.github.com/repos/{}/actions/secrets/public-key'.format(repos)
headers = {
'Accept': 'application/vnd.github+json',
'Authorization': 'Bearer {}'.format(token),
'X-GitHub-Api-Version': '2022-11-28'
}
r = requests.get(url, headers=headers)
return r.json()['key'], r.json()['key_id']
def update_secret(name: str, value: str) -> NoReturn:
"""
更新 secret
:param name: secret 名称
:param value: secret 值
:return:
"""
repos = environ['GITHUB_REPOS']
token = environ['GP_TOKEN']
if not token:
logging.error('未配置 GP_TOKEN, 更新 refresh_tokens 失败')
return
key, key_id = get_pub_key(repos, token)
url = 'https://api.github.com/repos/{}/actions/secrets/{}'.format(repos, name)
headers = {
'Accept': 'application/vnd.github+json',
'Authorization': 'Bearer {}'.format(token),
'X-GitHub-Api-Version': '2022-11-28'
}
payload = {
'encrypted_value': encrypt(key, value),
'key_id': key_id
}
requests.put(url, headers=headers, json=payload)