Debian Codegraph @

bin/ci/gitlab_common.py

raw
1 #!/usr/bin/env python3
2 # Copyright © 2020 - 2022 Collabora Ltd.
3 # Authors:
4 # Tomeu Vizoso <[email protected]>
5 # David Heidelberg <[email protected]>
6 # Guilherme Gallo <[email protected]>
7 #
8 # SPDX-License-Identifier: MIT
9 '''Shared functions between the scripts.'''
10
11 import logging
12 import os
13 import re
14 import time
15 from functools import cache
16 from pathlib import Path
17
18 GITLAB_URL = "https://gitlab.freedesktop.org"
19 TOKEN_DIR = Path(os.environ.get("XDG_CONFIG_HOME", "")
20 if os.environ.get("XDG_CONFIG_HOME", None)
21 else Path.home() / ".config")
22
23 # Known GitLab token prefixes: https://docs.gitlab.com/security/tokens/#token-prefixes
24 TOKEN_PREFIXES: dict[str, str] = {
25 "Personal access token": "glpat-",
26 "OAuth Application Secret": "gloas-",
27 "Deploy token": "gldt-",
28 "Runner authentication token": "glrt-",
29 "CI/CD Job token": "glcbt-",
30 "Trigger token": "glptt-",
31 "Feed token": "glft-",
32 "Incoming mail token": "glimt-",
33 "GitLab Agent for Kubernetes token": "glagent-",
34 "SCIM Tokens": "glsoat-",
35 }
36
37
38 @cache
39 def print_once(*args, **kwargs):
40 """Print without spamming the output"""
41 print(*args, **kwargs)
42
43
44 def pretty_duration(seconds: int | float) -> str:
45 """Pretty print duration"""
46 seconds = int(seconds)
47 hours, rem = divmod(seconds, 3600)
48 minutes, seconds = divmod(rem, 60)
49 if hours:
50 return f"{hours:0.0f}h{minutes:02.0f}m{seconds:02.0f}s"
51 if minutes:
52 return f"{minutes:0.0f}m{seconds:02.0f}s"
53 return f"{seconds:0.0f}s"
54
55
56 def get_gitlab_pipeline_from_url(gl, pipeline_url) -> tuple:
57 """
58 Extract the project and pipeline object from the url string
59 :param gl: Gitlab object
60 :param pipeline_url: string with a url to a pipeline
61 :return: ProjectPipeline, Project objects
62 """
63 pattern = rf"^{re.escape(GITLAB_URL)}/(.*)/-/pipelines/([0-9]+)$"
64 match = re.match(pattern, pipeline_url)
65 if not match:
66 raise AssertionError(f"url {pipeline_url} doesn't follow the pattern {pattern}")
67 namespace_with_project, pipeline_id = match.groups()
68 cur_project = gl.projects.get(namespace_with_project)
69 pipe = cur_project.pipelines.get(pipeline_id)
70 return pipe, cur_project
71
72
73 def get_gitlab_project(glab, name: str):
74 """Finds a specified gitlab project for given user"""
75 if "/" in name:
76 project_path = name
77 else:
78 glab.auth()
79 username = glab.user.username
80 project_path = f"{username}/{name}"
81 return glab.projects.get(project_path)
82
83
84 def get_token_from_default_dir() -> str:
85 """
86 Retrieves the GitLab token from the default directory.
87
88 Returns:
89 str: The path to the GitLab token file.
90
91 Raises:
92 FileNotFoundError: If the token file is not found.
93 """
94 token_file = TOKEN_DIR / "gitlab-token"
95 try:
96 return str(token_file.resolve())
97 except FileNotFoundError as ex:
98 print(
99 f"Could not find {token_file}, please provide a token file as an argument"
100 )
101 raise ex
102
103
104 def validate_gitlab_token(token: str) -> bool:
105 # Match against recognised token prefixes
106 token_suffix = None
107 for token_type, token_prefix in TOKEN_PREFIXES.items():
108 if token.startswith(token_prefix):
109 logging.info(f"Found probable token type: {token_type}")
110 token_suffix = token[len(token_prefix):]
111 break
112
113 if not token_suffix:
114 return False
115
116 # Basic validation of the token suffix based on:
117 # https://gitlab.com/gitlab-org/gitlab/-/blob/master/gems/gitlab-secret_detection/lib/gitleaks.toml
118 if not re.match(r"(\w+-)?[0-9a-zA-Z_\-]{20,64}", token_suffix):
119 return False
120
121 return True
122
123
124 def get_token_from_arg(token_arg: str | Path | None) -> str | None:
125 if not token_arg:
126 logging.info("No token provided.")
127 return None
128
129 token_path = Path(token_arg)
130 if token_path.is_file():
131 return read_token_from_file(token_path)
132
133 return handle_direct_token(token_path, token_arg)
134
135
136 def read_token_from_file(token_path: Path) -> str:
137 token = token_path.read_text().strip()
138 logging.info(f"Token read from file: {token_path}")
139 return token
140
141
142 def handle_direct_token(token_path: Path, token_arg: str | Path) -> str | None:
143 if token_path == Path(get_token_from_default_dir()):
144 logging.warning(
145 f"The default token file {token_path} was not found. "
146 "Please provide a token file or a token directly via --token arg."
147 )
148 return None
149 logging.info("Token provided directly as an argument.")
150 return str(token_arg)
151
152
153 def read_token(token_arg: str | Path | None) -> str | None:
154 token = get_token_from_arg(token_arg)
155 if token and not validate_gitlab_token(token):
156 logging.warning("The provided token is either an old token or does not seem to "
157 "be a valid token.")
158 logging.warning("Newer tokens are the ones created from a Gitlab 14.5+ instance.")
159 logging.warning("See https://about.gitlab.com/releases/2021/11/22/"
160 "gitlab-14-5-released/"
161 "#new-gitlab-access-token-prefix-and-detection")
162 return token
163
164
165 def wait_for_pipeline(projects, sha: str, timeout=None):
166 """await until pipeline appears in Gitlab"""
167 project_names = [project.path_with_namespace for project in projects]
168 print(f"⏲ for the pipeline to appear in {project_names}..", end="")
169 start_time = time.time()
170 while True:
171 for project in projects:
172 pipelines = project.pipelines.list(sha=sha)
173 if pipelines:
174 print("", flush=True)
175 return (pipelines[0], project)
176 print("", end=".", flush=True)
177 if timeout and time.time() - start_time > timeout:
178 print(" not found", flush=True)
179 return (None, None)
180 time.sleep(1)
181
182 @cache
183 def is_gitlab_job() -> bool:
184 return os.getenv("CI_JOB_ID") is not None