-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrotate-token.py
184 lines (146 loc) · 5.32 KB
/
rotate-token.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
#!/usr/bin/env python
import json
import os
from datetime import date, timedelta
import requests
def rotate_gitlab_variable(**arguments):
api_v4_url = arguments["api_v4_url"]
header = arguments["header"]
project_id = arguments["project_id"]
env_var = arguments["env_var"]
token = arguments["token"]
base_url = f"{api_v4_url}/projects/{project_id}/variables"
variables_url = f"{base_url}/{env_var}"
payload = {
"key": env_var,
"value": token,
"masked": "true",
}
try:
r = requests.get(variables_url, headers=header, verify=False)
r.raise_for_status()
except requests.exceptions.HTTPError as e:
if r.status_code == 404:
# The variable is not present, pass
pass
else:
raise SystemExit(e)
response = r.json()
if "key" in response and response["key"] == env_var:
print(f"Variable [name: '{env_var}'] already exists, update it")
try:
r = requests.put(variables_url, headers=header, verify=False, data=payload)
r.raise_for_status()
except requests.exceptions.HTTPError as e:
raise SystemExit(e)
else:
print(f"Create new variable [name: '{env_var}']")
try:
r = requests.post(base_url, headers=header, verify=False, data=payload)
r.raise_for_status()
except requests.exceptions.HTTPError as e:
raise SystemExit(e)
def rotate_gitlab_token(**arguments):
api_v4_url = arguments["api_v4_url"]
header = arguments["header"]
project_id = arguments["project_id"]
author = arguments["author"]
base_url = f"{api_v4_url}/projects/{project_id}/access_tokens"
expires_at = date.today() + timedelta(weeks=+1)
payload = {
"name": f"{author}",
"scopes": ["api"],
"expires_at": f"{str(expires_at)}",
}
# get the token id
try:
r = requests.get(base_url, headers=header, verify=False)
r.raise_for_status()
except requests.exceptions.HTTPError as e:
raise SystemExit(e)
response = r.json()
counter = 0
for index in range(len(response)):
if (
"name" in response[index]
and response[index]["name"] == author
and response[index]["revoked"] == False
and response[index]["scopes"] == ["api"]
):
position = counter
counter += 1
if counter == 1:
token_id = response[position]["id"]
elif counter > 1:
print("WARNING: There are more than one tokens!")
if "token_id" in locals() and isinstance(token_id, (int)):
print(f"Token [name: '{author}', id: '{token_id}'] already exists, delete it")
delete_url = f"{base_url}/{str(token_id)}"
try:
r = requests.delete(delete_url, headers=header, verify=False)
r.raise_for_status()
except requests.exceptions.HTTPError as e:
raise SystemExit(e)
print(f"Create new token [name: '{author}']")
content_type = {"Content-Type": "application/json"}
headers = {**header, **content_type}
try:
r = requests.post(base_url, headers=headers, verify=False, data=json.dumps(payload))
r.raise_for_status()
except requests.exceptions.HTTPError as e:
raise SystemExit(e)
return r.json()["token"]
def get_project_id(**arguments):
api_v4_url = arguments["api_v4_url"]
header = arguments["header"]
path_with_namespace = arguments["path_with_namespace"]
project = os.path.basename(path_with_namespace)
search_url = f"{api_v4_url}/search/?scope=projects&search={project}"
try:
r = requests.get(search_url, headers=header, verify=False)
r.raise_for_status()
except requests.exceptions.HTTPError as e:
raise SystemExit(e)
response = r.json()
for index in range(len(response)):
if (
"path_with_namespace" in response[index]
and response[index]["path_with_namespace"] == path_with_namespace
):
project_id = response[index]["id"]
return project_id
return "Invalid project"
def main():
api_v4_url = "https://gitlab.example.org/api/v4"
author = "Notes"
env_var = "GITLAB_TOKEN"
try:
header = {"PRIVATE-TOKEN": format(os.environ["GITLAB_TOKEN"])}
except KeyError:
print("Please set the 'GITLAB_TOKEN' environment variable")
exit(1)
for line in open("./projects.txt"):
li = line.strip()
if not li.startswith("#"):
path_with_namespace = line.rstrip()
print(f"Processing: '{path_with_namespace}'")
id = get_project_id(
api_v4_url=api_v4_url,
header=header,
path_with_namespace=path_with_namespace,
)
if isinstance(id, (int)):
token = rotate_gitlab_token(
api_v4_url=api_v4_url, header=header, author=author, project_id=id
)
rotate_gitlab_variable(
api_v4_url=api_v4_url,
header=header,
env_var=env_var,
token=token,
project_id=id,
)
else:
print(f"WARNING: '{path_with_namespace}' not found")
if __name__ == "__main__":
main()