hegemony-steps-git 0.59.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hegemony_steps_git/__init__.py +31 -0
- hegemony_steps_git/commit.py +1019 -0
- hegemony_steps_git/docs/git.commit.md +116 -0
- hegemony_steps_git-0.59.0.dist-info/METADATA +45 -0
- hegemony_steps_git-0.59.0.dist-info/RECORD +8 -0
- hegemony_steps_git-0.59.0.dist-info/WHEEL +4 -0
- hegemony_steps_git-0.59.0.dist-info/entry_points.txt +3 -0
- hegemony_steps_git-0.59.0.dist-info/licenses/LICENSE-AGPL-3.0-or-later.txt +235 -0
|
@@ -0,0 +1,1019 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Rexonix s.r.o.
|
|
2
|
+
# SPDX-FileContributor: Jakub Trávník <jakub.travnik@gmail.com>
|
|
3
|
+
#
|
|
4
|
+
# SPDX-License-Identifier: AGPL-3.0-or-later
|
|
5
|
+
|
|
6
|
+
"""``git.commit``: commit an earlier step's evidence to a Git repository.
|
|
7
|
+
|
|
8
|
+
The step takes the text evidence one earlier step recorded (the output of
|
|
9
|
+
``netcli.collect_evidence``, say: a running configuration per device), writes
|
|
10
|
+
each artifact to a file in a fresh clone of the repository's branch, and
|
|
11
|
+
commits and pushes only when a file changed. The repository's history is then
|
|
12
|
+
the history of what the step read.
|
|
13
|
+
|
|
14
|
+
It runs git in a container on the sandbox through ``container.run``'s runner,
|
|
15
|
+
like the other tool steps, so the flow's egress policy decides which Git
|
|
16
|
+
server it may reach. The login reaches git through ``GIT_ASKPASS`` from staged
|
|
17
|
+
files, never through the URL, an argument or an environment variable.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import re
|
|
23
|
+
import shlex
|
|
24
|
+
import time
|
|
25
|
+
from dataclasses import dataclass, field
|
|
26
|
+
from datetime import UTC, datetime
|
|
27
|
+
from typing import Any
|
|
28
|
+
from urllib.parse import urlsplit
|
|
29
|
+
|
|
30
|
+
from pydantic import Field, field_validator
|
|
31
|
+
|
|
32
|
+
from hegemony_step_sdk import (
|
|
33
|
+
BaseHandler,
|
|
34
|
+
HandlerContext,
|
|
35
|
+
HandlerResult,
|
|
36
|
+
HandlerTargeting,
|
|
37
|
+
InvalidConfigError,
|
|
38
|
+
OutputField,
|
|
39
|
+
StepKind,
|
|
40
|
+
)
|
|
41
|
+
from hegemony_step_sdk.trust import combined_ca_pem, org_trusted_ca_pem
|
|
42
|
+
from hegemony_steps_container.runner import (
|
|
43
|
+
KILL_AFTER_SECONDS,
|
|
44
|
+
OUTPUT_DIR,
|
|
45
|
+
ContainerExecutionConfig,
|
|
46
|
+
ContainerJob,
|
|
47
|
+
ContainerJobResult,
|
|
48
|
+
StagedFile,
|
|
49
|
+
container_config_from,
|
|
50
|
+
deadline_shell_lines,
|
|
51
|
+
is_bare_secret_ref,
|
|
52
|
+
report_timeout_cut,
|
|
53
|
+
resolve_secret_values,
|
|
54
|
+
run_container_job,
|
|
55
|
+
step_container_timeout,
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
HANDLER_ID = "git.commit"
|
|
59
|
+
|
|
60
|
+
#: The step's default image: Alpine with git and the CA bundle, built from
|
|
61
|
+
#: images/git-runner and published by the Images workflow for every release.
|
|
62
|
+
DEFAULT_IMAGE = "ghcr.io/hegemony-sh/git-runner:0.59"
|
|
63
|
+
|
|
64
|
+
#: Where the step's own files live in the container.
|
|
65
|
+
GIT_ROOT = "/hegemony/git"
|
|
66
|
+
RUN_SCRIPT = f"{GIT_ROOT}/run.sh"
|
|
67
|
+
ASKPASS_SCRIPT = f"{GIT_ROOT}/askpass.sh"
|
|
68
|
+
USERNAME_FILE = f"{GIT_ROOT}/username"
|
|
69
|
+
PASSWORD_FILE = f"{GIT_ROOT}/password"
|
|
70
|
+
MESSAGE_FILE = f"{GIT_ROOT}/message"
|
|
71
|
+
MANIFEST_FILE = f"{GIT_ROOT}/manifest"
|
|
72
|
+
CA_FILE = f"{GIT_ROOT}/ca-bundle.pem"
|
|
73
|
+
FILES_DIR = f"{GIT_ROOT}/files"
|
|
74
|
+
|
|
75
|
+
#: What the script reports, collected after the container exits.
|
|
76
|
+
CHANGED_OUT = f"{OUTPUT_DIR}/changed"
|
|
77
|
+
COMMIT_OUT = f"{OUTPUT_DIR}/commit"
|
|
78
|
+
CHANGED_FILES_OUT = f"{OUTPUT_DIR}/changed-files"
|
|
79
|
+
|
|
80
|
+
#: The script's own exit codes, for failures it can name.
|
|
81
|
+
EXIT_NO_BRANCH = 3
|
|
82
|
+
EXIT_UNSAFE_PATH = 4
|
|
83
|
+
EXIT_PUSH_REJECTED = 5
|
|
84
|
+
|
|
85
|
+
#: Times the script clones, commits and pushes again when the push is refused
|
|
86
|
+
#: (another run pushed to the branch in between).
|
|
87
|
+
PUSH_ATTEMPTS = 3
|
|
88
|
+
|
|
89
|
+
#: Largest file, and all files together, the step writes.
|
|
90
|
+
MAX_FILE_BYTES = 16 * 1024 * 1024
|
|
91
|
+
MAX_TOTAL_BYTES = 32 * 1024 * 1024
|
|
92
|
+
#: Most files one step writes.
|
|
93
|
+
MAX_FILES = 5000
|
|
94
|
+
#: Paths listed in the output; the evidence keeps them all.
|
|
95
|
+
MAX_OUTPUT_PATHS = 500
|
|
96
|
+
|
|
97
|
+
DEFAULT_PATH_TEMPLATE = "{device}/{command}.txt"
|
|
98
|
+
PLACEHOLDERS = ("device", "command", "name", "step")
|
|
99
|
+
|
|
100
|
+
_PLACEHOLDER_RE = re.compile(r"\{([^{}]*)\}")
|
|
101
|
+
_UNSAFE_CHAR_RE = re.compile(r"[^A-Za-z0-9._-]+")
|
|
102
|
+
#: A branch name git accepts, kept to a safe subset (git check-ref-format).
|
|
103
|
+
_BRANCH_RE = re.compile(r"^(?!/)(?!.*//)(?!.*\.\.)(?!.*@\{)[A-Za-z0-9._/-]+(?<![/.])$")
|
|
104
|
+
_TEMPLATE_RE = re.compile(r"\{\{|\{%")
|
|
105
|
+
#: A scheme written out before any template, as in ``http://{{ host }}/x.git``.
|
|
106
|
+
_LITERAL_SCHEME_RE = re.compile(r"^([A-Za-z][A-Za-z0-9+.-]*)://")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _is_templated(value: str) -> bool:
|
|
110
|
+
return bool(_TEMPLATE_RE.search(value))
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _is_secret_ref(value: str) -> bool:
|
|
114
|
+
text = value.strip()
|
|
115
|
+
return is_bare_secret_ref(text) or bool(_TEMPLATE_RE.search(text))
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def url_error(value: str, *, allow_templates: bool = False) -> str | None:
|
|
119
|
+
"""Why ``value`` cannot be the repository URL, or None.
|
|
120
|
+
|
|
121
|
+
With ``allow_templates`` (saving a flow), a URL that is still a template,
|
|
122
|
+
such as ``{{ vars.REPO_URL }}``, is accepted unless a scheme other than
|
|
123
|
+
https is written out in it: the step checks the rendered URL in full
|
|
124
|
+
before it runs.
|
|
125
|
+
"""
|
|
126
|
+
text = value.strip()
|
|
127
|
+
if not text:
|
|
128
|
+
return "'repository_url' is required"
|
|
129
|
+
if _is_templated(text):
|
|
130
|
+
if not allow_templates:
|
|
131
|
+
# Rendered by now: template markers left anywhere in it (the path
|
|
132
|
+
# included) mean it was not rendered, and git could not clone it.
|
|
133
|
+
return "'repository_url' still contains a template; it was not rendered"
|
|
134
|
+
literal = _LITERAL_SCHEME_RE.match(text)
|
|
135
|
+
if literal and literal.group(1).lower() != "https":
|
|
136
|
+
return "'repository_url' must be an https:// URL"
|
|
137
|
+
return None
|
|
138
|
+
try:
|
|
139
|
+
parts = urlsplit(text)
|
|
140
|
+
except ValueError:
|
|
141
|
+
return "'repository_url' is not a valid URL"
|
|
142
|
+
if parts.scheme != "https":
|
|
143
|
+
return "'repository_url' must be an https:// URL"
|
|
144
|
+
if not parts.hostname:
|
|
145
|
+
return "'repository_url' has no host"
|
|
146
|
+
if parts.username is not None or parts.password is not None:
|
|
147
|
+
return (
|
|
148
|
+
"'repository_url' must not carry a login; set Username and Password, which "
|
|
149
|
+
"reach git without appearing in the URL"
|
|
150
|
+
)
|
|
151
|
+
if parts.query or parts.fragment:
|
|
152
|
+
return "'repository_url' must not have a query or a fragment"
|
|
153
|
+
if any(char.isspace() or ord(char) < 32 for char in text):
|
|
154
|
+
return "'repository_url' must not contain spaces or control characters"
|
|
155
|
+
return None
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def branch_error(value: str, *, allow_templates: bool = False) -> str | None:
|
|
159
|
+
"""Why ``value`` cannot be the branch, or None.
|
|
160
|
+
|
|
161
|
+
With ``allow_templates`` (saving a flow), a templated branch is checked
|
|
162
|
+
once rendered, when the step runs.
|
|
163
|
+
"""
|
|
164
|
+
text = value.strip()
|
|
165
|
+
if allow_templates and _is_templated(text):
|
|
166
|
+
return None
|
|
167
|
+
if text.startswith("refs/"):
|
|
168
|
+
return "'branch' is a branch name such as main, not a ref"
|
|
169
|
+
if (
|
|
170
|
+
not _BRANCH_RE.match(text)
|
|
171
|
+
or text.startswith("-")
|
|
172
|
+
or text.endswith(".lock")
|
|
173
|
+
or any(part.startswith(".") for part in text.split("/"))
|
|
174
|
+
):
|
|
175
|
+
return f"'branch' {text!r} is not a valid branch name"
|
|
176
|
+
return None
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def path_template_error(value: str) -> str | None:
|
|
180
|
+
"""Why ``value`` cannot be the Path template, or None."""
|
|
181
|
+
text = value.strip()
|
|
182
|
+
if not text:
|
|
183
|
+
return "'path_template' is required"
|
|
184
|
+
for name in _PLACEHOLDER_RE.findall(text):
|
|
185
|
+
if name not in PLACEHOLDERS:
|
|
186
|
+
return f"'path_template' has an unknown placeholder {{{name}}}; use " + ", ".join(
|
|
187
|
+
f"{{{item}}}" for item in PLACEHOLDERS
|
|
188
|
+
)
|
|
189
|
+
stripped = _PLACEHOLDER_RE.sub("x", text)
|
|
190
|
+
if "{" in stripped or "}" in stripped:
|
|
191
|
+
return "'path_template' has an unmatched { or }"
|
|
192
|
+
return _relative_path_error(stripped, "'path_template'")
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _relative_path_error(path: str, what: str) -> str | None:
|
|
196
|
+
"""Why ``path`` is not a safe path inside the repository, or None."""
|
|
197
|
+
if path.startswith("/") or "\\" in path:
|
|
198
|
+
return f"{what} must be a relative path with / between folders"
|
|
199
|
+
if any(ord(char) < 32 or ord(char) == 127 for char in path):
|
|
200
|
+
return f"{what} must not contain control characters"
|
|
201
|
+
parts = path.split("/")
|
|
202
|
+
if any(part in ("", ".", "..") for part in parts):
|
|
203
|
+
return f"{what} must not have empty, . or .. segments"
|
|
204
|
+
if any(part.lower() == ".git" for part in parts):
|
|
205
|
+
return f"{what} must not reach into .git"
|
|
206
|
+
if path != path.strip():
|
|
207
|
+
return f"{what} must not start or end with spaces"
|
|
208
|
+
return None
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def safe_segment(value: str) -> str:
|
|
212
|
+
"""``value`` as one file-name segment: letters, digits, '.', '_' and '-' only."""
|
|
213
|
+
# No leading dot: no hidden files, and never "." or "..".
|
|
214
|
+
text = _UNSAFE_CHAR_RE.sub("_", value.strip()).lstrip("._").rstrip("_")
|
|
215
|
+
return text[:120] or "_"
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
class GitCommitConfig(ContainerExecutionConfig):
|
|
219
|
+
"""Config for ``git.commit``."""
|
|
220
|
+
|
|
221
|
+
repository_url: str = Field(
|
|
222
|
+
default="",
|
|
223
|
+
title="Repository URL",
|
|
224
|
+
description=(
|
|
225
|
+
"The repository's https:// clone URL, without a login. The flow's network "
|
|
226
|
+
"policy must allow the step to reach it."
|
|
227
|
+
),
|
|
228
|
+
json_schema_extra={
|
|
229
|
+
"x_placeholder": "https://git.example.com/netops/backups.git",
|
|
230
|
+
"x_col_span": 2,
|
|
231
|
+
},
|
|
232
|
+
)
|
|
233
|
+
branch: str = Field(
|
|
234
|
+
default="main",
|
|
235
|
+
title="Branch",
|
|
236
|
+
description="The branch to commit to. Defaults to main.",
|
|
237
|
+
json_schema_extra={"x_placeholder": "main"},
|
|
238
|
+
)
|
|
239
|
+
create_branch: bool = Field(
|
|
240
|
+
default=False,
|
|
241
|
+
title="Create the branch",
|
|
242
|
+
description=(
|
|
243
|
+
"Start the branch when it does not exist yet (needed for the first commit to "
|
|
244
|
+
"an empty repository). It starts empty, holding only this step's files. Off: "
|
|
245
|
+
"a missing branch fails the step."
|
|
246
|
+
),
|
|
247
|
+
)
|
|
248
|
+
username: str = Field(
|
|
249
|
+
default="",
|
|
250
|
+
title="Username",
|
|
251
|
+
description=(
|
|
252
|
+
"The Git login's user name: text, a secret reference or a "
|
|
253
|
+
"{{ secret('...') }} template. With a token, any name the server accepts "
|
|
254
|
+
"(GitHub takes x-access-token)."
|
|
255
|
+
),
|
|
256
|
+
json_schema_extra={"x_placeholder": "backup-bot"},
|
|
257
|
+
)
|
|
258
|
+
password: str = Field(
|
|
259
|
+
default="",
|
|
260
|
+
title="Password or Token",
|
|
261
|
+
description=(
|
|
262
|
+
"The Git login's password or access token: a secret reference such as "
|
|
263
|
+
"vault://orgs/acme/secrets/git/token, or a {{ secret('...') }} template. A "
|
|
264
|
+
"value written in clear is refused. Empty: no login."
|
|
265
|
+
),
|
|
266
|
+
json_schema_extra={
|
|
267
|
+
"x_placeholder": "vault://orgs/acme/secrets/git/token",
|
|
268
|
+
"x_col_span": 2,
|
|
269
|
+
},
|
|
270
|
+
)
|
|
271
|
+
source_step: str = Field(
|
|
272
|
+
default="",
|
|
273
|
+
title="Evidence Step",
|
|
274
|
+
description=(
|
|
275
|
+
"The earlier step whose evidence is committed, such as a "
|
|
276
|
+
"netcli.collect_evidence step. Its newest artifact per device and command is "
|
|
277
|
+
"written; failed captures are skipped."
|
|
278
|
+
),
|
|
279
|
+
json_schema_extra={"x_widget": "step-select", "x_placeholder": "Select a step..."},
|
|
280
|
+
)
|
|
281
|
+
path_template: str = Field(
|
|
282
|
+
default=DEFAULT_PATH_TEMPLATE,
|
|
283
|
+
title="Path",
|
|
284
|
+
description=(
|
|
285
|
+
"Where each artifact is written in the repository. {device} is the device "
|
|
286
|
+
"name, {command} the command, {name} the artifact's name and {step} the "
|
|
287
|
+
"evidence step's id, each made safe for a file name. Defaults to "
|
|
288
|
+
"{device}/{command}.txt."
|
|
289
|
+
),
|
|
290
|
+
json_schema_extra={"x_placeholder": "configs/{device}.cfg", "x_col_span": 2},
|
|
291
|
+
)
|
|
292
|
+
commit_message: str = Field(
|
|
293
|
+
default="",
|
|
294
|
+
title="Commit Message",
|
|
295
|
+
description=(
|
|
296
|
+
"The commit's message. Empty: 'Hegemony: <flow> run <run id>'. Templates "
|
|
297
|
+
"such as {{ run_id }} are filled in."
|
|
298
|
+
),
|
|
299
|
+
json_schema_extra={"x_widget": "textarea", "x_rows": 3, "x_col_span": 2},
|
|
300
|
+
)
|
|
301
|
+
author_name: str = Field(
|
|
302
|
+
default="Hegemony",
|
|
303
|
+
title="Author Name",
|
|
304
|
+
description="The commit's author and committer name. Defaults to Hegemony.",
|
|
305
|
+
json_schema_extra={"x_advanced": True},
|
|
306
|
+
)
|
|
307
|
+
author_email: str = Field(
|
|
308
|
+
default="hegemony@localhost",
|
|
309
|
+
title="Author Email",
|
|
310
|
+
description="The commit's author and committer email. Defaults to hegemony@localhost.",
|
|
311
|
+
json_schema_extra={"x_advanced": True},
|
|
312
|
+
)
|
|
313
|
+
trusted_cas: bool = Field(
|
|
314
|
+
default=False,
|
|
315
|
+
title="Trust the organization's CAs",
|
|
316
|
+
description=(
|
|
317
|
+
"Let git trust the organization's trusted CAs (Settings, Trusted CAs) as well "
|
|
318
|
+
"as the public ones, for a Git server whose certificate a private CA signed."
|
|
319
|
+
),
|
|
320
|
+
json_schema_extra={"x_advanced": True},
|
|
321
|
+
)
|
|
322
|
+
image: str = Field(
|
|
323
|
+
default=DEFAULT_IMAGE,
|
|
324
|
+
min_length=1,
|
|
325
|
+
title="Execution image",
|
|
326
|
+
description=(
|
|
327
|
+
"Container image with git and /bin/sh. Change it only to pull the default "
|
|
328
|
+
"image from a mirror."
|
|
329
|
+
),
|
|
330
|
+
json_schema_extra={"x_advanced": True, "x_col_span": 2},
|
|
331
|
+
)
|
|
332
|
+
cache_image: bool = Field(
|
|
333
|
+
default=True,
|
|
334
|
+
title="Cache image",
|
|
335
|
+
description=(
|
|
336
|
+
"Keep a copy of the pulled image in the platform registry, under this "
|
|
337
|
+
"organization, and use it on later runs. No effect when the platform runs no "
|
|
338
|
+
"registry."
|
|
339
|
+
),
|
|
340
|
+
json_schema_extra={"x_advanced": True},
|
|
341
|
+
)
|
|
342
|
+
|
|
343
|
+
@field_validator("author_name", "author_email")
|
|
344
|
+
@classmethod
|
|
345
|
+
def _one_line(cls, value: str) -> str:
|
|
346
|
+
if any(ord(char) < 32 or char in "<>" for char in value):
|
|
347
|
+
raise ValueError("must be one line without < or >")
|
|
348
|
+
return value
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def config_errors(config: GitCommitConfig, *, allow_templates: bool = False) -> list[str]:
|
|
352
|
+
"""Checks across fields that the model's own validators cannot make.
|
|
353
|
+
|
|
354
|
+
``allow_templates`` is for saving a flow, when the repository URL and
|
|
355
|
+
branch may still be templates; the step runs these checks again on the
|
|
356
|
+
rendered values before it commits anything.
|
|
357
|
+
"""
|
|
358
|
+
errors = [
|
|
359
|
+
error
|
|
360
|
+
for error in (
|
|
361
|
+
url_error(config.repository_url, allow_templates=allow_templates),
|
|
362
|
+
branch_error(config.branch, allow_templates=allow_templates),
|
|
363
|
+
path_template_error(config.path_template),
|
|
364
|
+
)
|
|
365
|
+
if error
|
|
366
|
+
]
|
|
367
|
+
if not config.source_step.strip():
|
|
368
|
+
errors.append("'source_step' is required: choose the step whose evidence is committed")
|
|
369
|
+
if config.password.strip() and not _is_secret_ref(config.password):
|
|
370
|
+
errors.append(
|
|
371
|
+
"'password' must be a secret reference or a {{ secret('...') }} template; a "
|
|
372
|
+
"value written in clear would be stored in the flow and not redacted"
|
|
373
|
+
)
|
|
374
|
+
if config.password.strip() and not config.username.strip():
|
|
375
|
+
errors.append("'username' is required with a password or token")
|
|
376
|
+
if not config.author_name.strip() or not config.author_email.strip():
|
|
377
|
+
errors.append("'author_name' and 'author_email' must not be empty")
|
|
378
|
+
return errors
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
# --- Choosing the files ------------------------------------------------------
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
@dataclass
|
|
385
|
+
class Selection:
|
|
386
|
+
"""The files to write, and what was left out and why."""
|
|
387
|
+
|
|
388
|
+
files: dict[str, str] = field(default_factory=dict)
|
|
389
|
+
skipped: list[str] = field(default_factory=list)
|
|
390
|
+
errors: list[str] = field(default_factory=list)
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _created_at(artifact: dict[str, Any]) -> datetime | None:
|
|
394
|
+
value = artifact.get("created_at")
|
|
395
|
+
if not isinstance(value, str) or not value:
|
|
396
|
+
return None
|
|
397
|
+
try:
|
|
398
|
+
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
399
|
+
except ValueError:
|
|
400
|
+
return None
|
|
401
|
+
return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def _metadata(artifact: dict[str, Any]) -> dict[str, Any]:
|
|
405
|
+
meta = artifact.get("content_json")
|
|
406
|
+
return meta if isinstance(meta, dict) else {}
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _capture_key(artifact: dict[str, Any]) -> tuple[str, ...]:
|
|
410
|
+
"""One capture: the device and full command a netcli step records, else the name."""
|
|
411
|
+
meta = _metadata(artifact)
|
|
412
|
+
if isinstance(meta.get("command"), str):
|
|
413
|
+
return (
|
|
414
|
+
"command",
|
|
415
|
+
str(meta.get("device_id")),
|
|
416
|
+
str(meta.get("device_name")),
|
|
417
|
+
meta["command"].strip(),
|
|
418
|
+
)
|
|
419
|
+
return ("name", str(artifact.get("name") or ""))
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def newest_captures(artifacts: list[dict[str, Any]], step_id: str) -> list[dict[str, Any]]:
|
|
423
|
+
"""The newest artifact of ``step_id`` per capture, in the order they were first seen.
|
|
424
|
+
|
|
425
|
+
A step that runs more than once (loop iterations, retries) adds artifacts
|
|
426
|
+
with the same device and command each time; the newest wins. Artifacts
|
|
427
|
+
without a usable ``created_at`` sort below dated ones, and among
|
|
428
|
+
themselves the last one listed wins (the API lists oldest first).
|
|
429
|
+
"""
|
|
430
|
+
best: dict[tuple[str, ...], dict[str, Any]] = {}
|
|
431
|
+
for artifact in artifacts:
|
|
432
|
+
if artifact.get("step_id") != step_id:
|
|
433
|
+
continue
|
|
434
|
+
key = _capture_key(artifact)
|
|
435
|
+
if key == ("name", ""):
|
|
436
|
+
continue
|
|
437
|
+
current = best.get(key)
|
|
438
|
+
if current is None:
|
|
439
|
+
best[key] = artifact
|
|
440
|
+
continue
|
|
441
|
+
new_at, old_at = _created_at(artifact), _created_at(current)
|
|
442
|
+
if new_at is None and old_at is not None:
|
|
443
|
+
continue
|
|
444
|
+
if new_at is None or old_at is None or new_at >= old_at:
|
|
445
|
+
best[key] = artifact
|
|
446
|
+
return list(best.values())
|
|
447
|
+
|
|
448
|
+
|
|
449
|
+
def _device_key(meta: dict[str, Any]) -> str | None:
|
|
450
|
+
"""The device an artifact's record names: its id, else its name."""
|
|
451
|
+
for field_name in ("device_id", "device_name"):
|
|
452
|
+
value = meta.get(field_name)
|
|
453
|
+
if isinstance(value, str) and value:
|
|
454
|
+
return f"{field_name}:{value}"
|
|
455
|
+
return None
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
_UNDATED = datetime.min.replace(tzinfo=UTC)
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def _order(artifact: dict[str, Any], position: int) -> tuple[int, datetime, int]:
|
|
462
|
+
"""Sort key for "newer": dated after undated, then by date, then by list position."""
|
|
463
|
+
created = _created_at(artifact)
|
|
464
|
+
return (0, _UNDATED, position) if created is None else (1, created, position)
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def newest_device_failures(
|
|
468
|
+
artifacts: list[dict[str, Any]], step_id: str
|
|
469
|
+
) -> dict[str, tuple[tuple[int, datetime, int], str]]:
|
|
470
|
+
"""Each device's newest device-wide failure (an error with no command), with its order key.
|
|
471
|
+
|
|
472
|
+
``netcli.collect_evidence`` records a device it could not reach as one
|
|
473
|
+
``error`` artifact without a command, so it never shares a capture key
|
|
474
|
+
with the device's command outputs.
|
|
475
|
+
"""
|
|
476
|
+
failures: dict[str, tuple[tuple[int, datetime, int], str]] = {}
|
|
477
|
+
for position, artifact in enumerate(artifacts):
|
|
478
|
+
meta = _metadata(artifact)
|
|
479
|
+
if artifact.get("step_id") != step_id or artifact.get("kind") != "error":
|
|
480
|
+
continue
|
|
481
|
+
if isinstance(meta.get("command"), str):
|
|
482
|
+
continue
|
|
483
|
+
device = _device_key(meta)
|
|
484
|
+
if device is None:
|
|
485
|
+
continue
|
|
486
|
+
key = _order(artifact, position)
|
|
487
|
+
if device not in failures or key >= failures[device][0]:
|
|
488
|
+
failures[device] = (key, str(meta.get("error") or "the capture failed"))
|
|
489
|
+
return failures
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def _label(artifact: dict[str, Any]) -> str:
|
|
493
|
+
meta = _metadata(artifact)
|
|
494
|
+
if isinstance(meta.get("command"), str):
|
|
495
|
+
return f"{meta.get('device_name') or '?'}:{meta['command'].strip().splitlines()[0][:80]}"
|
|
496
|
+
return str(artifact.get("name") or artifact.get("id") or "?")
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def _failure(artifact: dict[str, Any]) -> str | None:
|
|
500
|
+
"""Why the capture holds no usable output, or None."""
|
|
501
|
+
meta = _metadata(artifact)
|
|
502
|
+
if artifact.get("kind") == "error":
|
|
503
|
+
return str(meta.get("error") or "the capture failed")
|
|
504
|
+
if meta.get("success") is False:
|
|
505
|
+
return str(meta.get("error") or f"the command failed (exit code {meta.get('exit_code')})")
|
|
506
|
+
if not isinstance(artifact.get("content_text"), str):
|
|
507
|
+
return "it has no text content"
|
|
508
|
+
return None
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
def render_path(template: str, artifact: dict[str, Any], step_id: str) -> str:
|
|
512
|
+
"""The repository path ``template`` gives ``artifact``.
|
|
513
|
+
|
|
514
|
+
Raises ``ValueError`` when the template needs a device the artifact has
|
|
515
|
+
none for.
|
|
516
|
+
"""
|
|
517
|
+
meta = _metadata(artifact)
|
|
518
|
+
command = meta.get("command") if isinstance(meta.get("command"), str) else None
|
|
519
|
+
device = meta.get("device_name") or artifact.get("device_name")
|
|
520
|
+
name = str(artifact.get("name") or artifact.get("id") or "")
|
|
521
|
+
if "{device}" in template and not device:
|
|
522
|
+
raise ValueError("it has no device; use {name} in Path instead of {device}")
|
|
523
|
+
values = {
|
|
524
|
+
"device": safe_segment(str(device or "")),
|
|
525
|
+
"command": safe_segment(command if command is not None else name),
|
|
526
|
+
"name": safe_segment(name),
|
|
527
|
+
"step": safe_segment(step_id),
|
|
528
|
+
}
|
|
529
|
+
return _PLACEHOLDER_RE.sub(lambda match: values[match.group(1)], template.strip())
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def select_files(artifacts: list[dict[str, Any]], step_id: str, template: str) -> Selection:
|
|
533
|
+
"""The files to write from ``step_id``'s artifacts, keyed by repository path."""
|
|
534
|
+
selection = Selection()
|
|
535
|
+
total = 0
|
|
536
|
+
owners: dict[str, str] = {}
|
|
537
|
+
positions = {id(artifact): position for position, artifact in enumerate(artifacts)}
|
|
538
|
+
device_failures = newest_device_failures(artifacts, step_id)
|
|
539
|
+
for artifact in newest_captures(artifacts, step_id):
|
|
540
|
+
label = _label(artifact)
|
|
541
|
+
failure = _failure(artifact)
|
|
542
|
+
meta = _metadata(artifact)
|
|
543
|
+
device = _device_key(meta)
|
|
544
|
+
if failure is None and isinstance(meta.get("command"), str) and device in device_failures:
|
|
545
|
+
# The device failed after this capture was read (a later loop
|
|
546
|
+
# iteration or retry): keep the repository's file as it is.
|
|
547
|
+
failed_at, reason = device_failures[device]
|
|
548
|
+
if failed_at > _order(artifact, positions[id(artifact)]):
|
|
549
|
+
failure = f"a later attempt failed: {reason}"
|
|
550
|
+
if failure:
|
|
551
|
+
selection.skipped.append(f"{label}: {failure}")
|
|
552
|
+
continue
|
|
553
|
+
try:
|
|
554
|
+
path = render_path(template, artifact, step_id)
|
|
555
|
+
except ValueError as exc:
|
|
556
|
+
selection.errors.append(f"{label}: {exc}")
|
|
557
|
+
continue
|
|
558
|
+
error = _relative_path_error(path, f"the path {path!r}")
|
|
559
|
+
if error:
|
|
560
|
+
selection.errors.append(f"{label}: {error}")
|
|
561
|
+
continue
|
|
562
|
+
if path in owners:
|
|
563
|
+
selection.errors.append(
|
|
564
|
+
f"{owners[path]} and {label} would both be written to {path}; put "
|
|
565
|
+
"{device} and {command} in Path"
|
|
566
|
+
)
|
|
567
|
+
continue
|
|
568
|
+
content = artifact["content_text"]
|
|
569
|
+
size = len(content.encode("utf-8"))
|
|
570
|
+
if size > MAX_FILE_BYTES:
|
|
571
|
+
selection.errors.append(f"{label}: larger than {MAX_FILE_BYTES // (1024 * 1024)} MiB")
|
|
572
|
+
continue
|
|
573
|
+
total += size
|
|
574
|
+
owners[path] = label
|
|
575
|
+
selection.files[path] = content
|
|
576
|
+
if total > MAX_TOTAL_BYTES:
|
|
577
|
+
selection.errors.append(
|
|
578
|
+
f"the files add up to more than {MAX_TOTAL_BYTES // (1024 * 1024)} MiB"
|
|
579
|
+
)
|
|
580
|
+
if len(selection.files) > MAX_FILES:
|
|
581
|
+
selection.errors.append(f"more than {MAX_FILES} files")
|
|
582
|
+
return selection
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
# --- The script --------------------------------------------------------------
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def _config_env_lines(settings: dict[str, str]) -> list[str]:
|
|
589
|
+
"""Shell lines that give every git call ``settings`` (GIT_CONFIG_COUNT, git 2.31+)."""
|
|
590
|
+
lines = [f"export GIT_CONFIG_COUNT={len(settings)}"]
|
|
591
|
+
for index, (key, value) in enumerate(settings.items()):
|
|
592
|
+
lines.append(
|
|
593
|
+
f"export GIT_CONFIG_KEY_{index}={shlex.quote(key)} "
|
|
594
|
+
f"GIT_CONFIG_VALUE_{index}={shlex.quote(value)}"
|
|
595
|
+
)
|
|
596
|
+
return lines
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def build_script(
|
|
600
|
+
*,
|
|
601
|
+
url: str,
|
|
602
|
+
branch: str,
|
|
603
|
+
create_branch: bool,
|
|
604
|
+
deadline: int,
|
|
605
|
+
login: bool,
|
|
606
|
+
ca_bundle: bool,
|
|
607
|
+
kill_after: int = KILL_AFTER_SECONDS,
|
|
608
|
+
root: str = GIT_ROOT,
|
|
609
|
+
out: str = OUTPUT_DIR,
|
|
610
|
+
allow_file_protocol: bool = False,
|
|
611
|
+
) -> str:
|
|
612
|
+
"""The POSIX shell script the container runs.
|
|
613
|
+
|
|
614
|
+
``root`` and ``out`` are the container paths of the step's files and of
|
|
615
|
+
its report. Tests run the script outside a container, with other paths
|
|
616
|
+
and a ``file://`` repository (``allow_file_protocol``); the step itself
|
|
617
|
+
allows git only https.
|
|
618
|
+
"""
|
|
619
|
+
q = shlex.quote
|
|
620
|
+
lines = [
|
|
621
|
+
"#!/bin/sh",
|
|
622
|
+
"# Generated by the git.commit step.",
|
|
623
|
+
"set -eu",
|
|
624
|
+
"umask 022",
|
|
625
|
+
f"out={q(out)}",
|
|
626
|
+
f"root={q(root)}",
|
|
627
|
+
'mkdir -p "$out"',
|
|
628
|
+
*deadline_shell_lines(deadline, kill_after),
|
|
629
|
+
f"url={q(url)}",
|
|
630
|
+
f"branch={q(branch)}",
|
|
631
|
+
f"create_branch={'yes' if create_branch else 'no'}",
|
|
632
|
+
'work="$(mktemp -d)"',
|
|
633
|
+
'export HOME="$work/home"',
|
|
634
|
+
'mkdir -p "$HOME"',
|
|
635
|
+
# No prompt, no system or global config, no hooks, no credential store.
|
|
636
|
+
# The step's own Environment Variables reach this shell too: drop every
|
|
637
|
+
# GIT_* variable but the commit identity, so none can undo what follows
|
|
638
|
+
# (GIT_CONFIG_PARAMETERS, GIT_SSL_NO_VERIFY, GIT_ALLOW_PROTOCOL, ...).
|
|
639
|
+
'for name in $(env | sed -n "s/^\\(GIT_[A-Za-z0-9_]*\\)=.*/\\1/p"); do',
|
|
640
|
+
' case "$name" in',
|
|
641
|
+
" GIT_AUTHOR_NAME|GIT_AUTHOR_EMAIL|GIT_COMMITTER_NAME|GIT_COMMITTER_EMAIL) ;;",
|
|
642
|
+
' *) unset "$name" ;;',
|
|
643
|
+
" esac",
|
|
644
|
+
"done",
|
|
645
|
+
"unset SSH_ASKPASS",
|
|
646
|
+
"export GIT_TERMINAL_PROMPT=0 GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null",
|
|
647
|
+
# Paths are file names, never patterns (:(glob), *, ...).
|
|
648
|
+
"export GIT_LITERAL_PATHSPECS=1",
|
|
649
|
+
"export GIT_PROTOCOL_FROM_USER=0",
|
|
650
|
+
# Settings every git call gets, also under `timeout`, which cannot run
|
|
651
|
+
# a shell function: no hooks, no fsmonitor, HTTPS only, no stored
|
|
652
|
+
# credentials, redirects only on the first request.
|
|
653
|
+
*_config_env_lines(
|
|
654
|
+
{
|
|
655
|
+
"core.hooksPath": "/dev/null",
|
|
656
|
+
"core.fsmonitor": "false",
|
|
657
|
+
"protocol.allow": "never",
|
|
658
|
+
"protocol.https.allow": "always",
|
|
659
|
+
"protocol.file.allow": "always" if allow_file_protocol else "never",
|
|
660
|
+
"credential.helper": "",
|
|
661
|
+
"http.followRedirects": "initial",
|
|
662
|
+
}
|
|
663
|
+
),
|
|
664
|
+
]
|
|
665
|
+
if login:
|
|
666
|
+
lines.append('export GIT_ASKPASS="$root/askpass.sh"')
|
|
667
|
+
if ca_bundle:
|
|
668
|
+
lines.append('export GIT_SSL_CAINFO="$root/ca-bundle.pem"')
|
|
669
|
+
lines += [
|
|
670
|
+
'repo="$work/repo"',
|
|
671
|
+
"attempt=1",
|
|
672
|
+
"while :; do",
|
|
673
|
+
' rm -rf "$repo"',
|
|
674
|
+
" status=0",
|
|
675
|
+
' bounded git ls-remote --exit-code --heads -- "$url" "refs/heads/$branch" '
|
|
676
|
+
+ ">/dev/null || status=$?",
|
|
677
|
+
' case "$status" in',
|
|
678
|
+
" 0)",
|
|
679
|
+
" bounded git clone --quiet --depth 1 --single-branch --no-tags "
|
|
680
|
+
+ '--branch "$branch" -- "$url" "$repo"',
|
|
681
|
+
" ;;",
|
|
682
|
+
" 2)",
|
|
683
|
+
' if [ "$create_branch" != yes ]; then',
|
|
684
|
+
' echo "branch $branch does not exist in the repository" >&2',
|
|
685
|
+
f" exit {EXIT_NO_BRANCH}",
|
|
686
|
+
" fi",
|
|
687
|
+
' git init --quiet "$repo"',
|
|
688
|
+
' git -C "$repo" remote add origin "$url"',
|
|
689
|
+
' git -C "$repo" checkout --quiet --orphan "$branch"',
|
|
690
|
+
" ;;",
|
|
691
|
+
' *) exit "$status" ;;',
|
|
692
|
+
" esac",
|
|
693
|
+
# Every path the step writes, checked against symbolic links in the
|
|
694
|
+
# clone: a link would carry the write out of the working tree.
|
|
695
|
+
" while IFS= read -r line; do",
|
|
696
|
+
' index="${line%% *}"',
|
|
697
|
+
' path="${line#* }"',
|
|
698
|
+
' probe="$repo"',
|
|
699
|
+
' rest="$path"',
|
|
700
|
+
" while :; do",
|
|
701
|
+
' part="${rest%%/*}"',
|
|
702
|
+
' probe="$probe/$part"',
|
|
703
|
+
' if [ -L "$probe" ]; then',
|
|
704
|
+
' echo "the repository has a symbolic link at ${probe#"$repo"/}; not writing $path" >&2',
|
|
705
|
+
f" exit {EXIT_UNSAFE_PATH}",
|
|
706
|
+
" fi",
|
|
707
|
+
' [ "$rest" = "$part" ] && break',
|
|
708
|
+
' rest="${rest#*/}"',
|
|
709
|
+
" done",
|
|
710
|
+
' if [ -e "$repo/$path" ] && [ ! -f "$repo/$path" ]; then',
|
|
711
|
+
' echo "$path exists in the repository and is not a file" >&2',
|
|
712
|
+
f" exit {EXIT_UNSAFE_PATH}",
|
|
713
|
+
" fi",
|
|
714
|
+
' mkdir -p "$(dirname "$repo/$path")"',
|
|
715
|
+
' cat "$root/files/$index" > "$repo/$path"',
|
|
716
|
+
' git -C "$repo" add --force -- "$path"',
|
|
717
|
+
' done < "$root/manifest"',
|
|
718
|
+
' if git -C "$repo" diff --cached --quiet; then',
|
|
719
|
+
' echo no > "$out/changed"',
|
|
720
|
+
' git -C "$repo" rev-parse --verify --quiet HEAD > "$out/commit" || : > "$out/commit"',
|
|
721
|
+
" exit 0",
|
|
722
|
+
" fi",
|
|
723
|
+
' git -C "$repo" diff --cached --name-only -z > "$out/changed-files"',
|
|
724
|
+
' git -C "$repo" commit --quiet --no-verify --no-gpg-sign -F "$root/message"',
|
|
725
|
+
" push=0",
|
|
726
|
+
' bounded git -C "$repo" push --porcelain origin "HEAD:refs/heads/$branch" '
|
|
727
|
+
+ '> "$work/push" 2>&1 || push=$?',
|
|
728
|
+
' if [ "$push" = 0 ]; then',
|
|
729
|
+
' echo yes > "$out/changed"',
|
|
730
|
+
' git -C "$repo" rev-parse HEAD > "$out/commit"',
|
|
731
|
+
" exit 0",
|
|
732
|
+
" fi",
|
|
733
|
+
' cat "$work/push" >&2',
|
|
734
|
+
# A refusal of an update that is not a fast-forward: another run
|
|
735
|
+
# pushed in between. Start over from the new branch head.
|
|
736
|
+
' if grep -Eq "^!.*\\[rejected\\]" "$work/push" '
|
|
737
|
+
+ f'&& [ "$attempt" -lt {PUSH_ATTEMPTS} ]; then',
|
|
738
|
+
" attempt=$((attempt + 1))",
|
|
739
|
+
' echo "the branch moved while committing; trying again ($attempt)" >&2',
|
|
740
|
+
" continue",
|
|
741
|
+
" fi",
|
|
742
|
+
' if grep -q "^!" "$work/push"; then',
|
|
743
|
+
f" exit {EXIT_PUSH_REJECTED}",
|
|
744
|
+
" fi",
|
|
745
|
+
' exit "$push"',
|
|
746
|
+
"done",
|
|
747
|
+
]
|
|
748
|
+
return "\n".join(lines) + "\n"
|
|
749
|
+
|
|
750
|
+
|
|
751
|
+
ASKPASS = """#!/bin/sh
|
|
752
|
+
# git asks for the user name and then the password; answer from the staged files.
|
|
753
|
+
case "$1" in
|
|
754
|
+
Username*) cat "{username}" ;;
|
|
755
|
+
*) cat "{password}" ;;
|
|
756
|
+
esac
|
|
757
|
+
"""
|
|
758
|
+
|
|
759
|
+
|
|
760
|
+
def _message(config: GitCommitConfig, ctx: HandlerContext) -> str:
|
|
761
|
+
text = config.commit_message.strip()
|
|
762
|
+
if text:
|
|
763
|
+
return text + "\n"
|
|
764
|
+
flow = ctx.flow_name or ctx.flow_id
|
|
765
|
+
return f"Hegemony: {flow} run {ctx.run_id}\n"
|
|
766
|
+
|
|
767
|
+
|
|
768
|
+
def _decode(outcome: ContainerJobResult, path: str) -> str:
|
|
769
|
+
return (outcome.collected.get(path) or b"").decode("utf-8", "replace")
|
|
770
|
+
|
|
771
|
+
|
|
772
|
+
def failure_message(outcome: ContainerJobResult, branch: str) -> str:
|
|
773
|
+
"""The step error for a script that exited non-zero."""
|
|
774
|
+
if outcome.exit_code == EXIT_NO_BRANCH:
|
|
775
|
+
return (
|
|
776
|
+
f"the branch {branch!r} does not exist in the repository; turn on Create the "
|
|
777
|
+
"branch to start it"
|
|
778
|
+
)
|
|
779
|
+
if outcome.exit_code == EXIT_UNSAFE_PATH:
|
|
780
|
+
return (
|
|
781
|
+
"the repository holds a symbolic link or a folder where the step writes a file; "
|
|
782
|
+
"see the container output"
|
|
783
|
+
)
|
|
784
|
+
if outcome.exit_code == EXIT_PUSH_REJECTED:
|
|
785
|
+
return "the server refused the push; see the container output"
|
|
786
|
+
text = f"{outcome.stdout}\n{outcome.stderr}"
|
|
787
|
+
if "Authentication failed" in text or "could not read Username" in text:
|
|
788
|
+
return "git could not log in to the repository: check Username and Password or Token"
|
|
789
|
+
if "SSL certificate problem" in text or "server certificate verification failed" in text:
|
|
790
|
+
return (
|
|
791
|
+
"git does not trust the server's certificate: turn on Trust the organization's "
|
|
792
|
+
"CAs if a private CA signed it"
|
|
793
|
+
)
|
|
794
|
+
if "Could not resolve host" in text or "Failed to connect" in text:
|
|
795
|
+
return "git could not reach the repository; check the URL and the flow's network policy"
|
|
796
|
+
return f"git exited with code {outcome.exit_code}; see the container output"
|
|
797
|
+
|
|
798
|
+
|
|
799
|
+
def _capped(paths: list[str]) -> list[str]:
|
|
800
|
+
return paths[:MAX_OUTPUT_PATHS]
|
|
801
|
+
|
|
802
|
+
|
|
803
|
+
class GitCommitHandler(BaseHandler):
|
|
804
|
+
"""Commit an earlier step's evidence to a Git repository, only when it changed."""
|
|
805
|
+
|
|
806
|
+
handler_id = HANDLER_ID
|
|
807
|
+
supported_kinds = [StepKind.ACTION, StepKind.EXECUTE]
|
|
808
|
+
display_name = "Git Commit"
|
|
809
|
+
description = "Commit an earlier step's evidence to a Git repository when it changed."
|
|
810
|
+
category = "Actions"
|
|
811
|
+
targeting = HandlerTargeting(roles=False, ips=False)
|
|
812
|
+
container_backed = True
|
|
813
|
+
# The login reaches the handler as written, so it resolves it itself and
|
|
814
|
+
# can refuse a password written in clear.
|
|
815
|
+
raw_config_keys = frozenset({"username", "password"})
|
|
816
|
+
config_model = GitCommitConfig
|
|
817
|
+
default_config = {"branch": "main", "path_template": DEFAULT_PATH_TEMPLATE}
|
|
818
|
+
run_timeout_field = "timeout_seconds"
|
|
819
|
+
output_fields = (
|
|
820
|
+
OutputField("changed", "Whether a commit was pushed (false when nothing changed)", "bool"),
|
|
821
|
+
OutputField(
|
|
822
|
+
"commit", "The branch head after the step: the new commit, or the old head", "string"
|
|
823
|
+
),
|
|
824
|
+
OutputField("branch", "The branch committed to", "string"),
|
|
825
|
+
OutputField("files", "Repository paths the step wrote", "list"),
|
|
826
|
+
OutputField("changed_files", "Paths the commit changed", "list"),
|
|
827
|
+
OutputField("skipped", "Captures left out, with the reason", "list"),
|
|
828
|
+
)
|
|
829
|
+
|
|
830
|
+
def validate_config(self, config: dict[str, Any]) -> list[str]:
|
|
831
|
+
errors = super().validate_config(config)
|
|
832
|
+
if errors:
|
|
833
|
+
return errors
|
|
834
|
+
return config_errors(GitCommitConfig.model_validate(config), allow_templates=True)
|
|
835
|
+
|
|
836
|
+
async def execute(self, ctx: HandlerContext) -> HandlerResult:
|
|
837
|
+
try:
|
|
838
|
+
config = self.parse_config(ctx.config, GitCommitConfig)
|
|
839
|
+
except InvalidConfigError as exc:
|
|
840
|
+
return exc.result()
|
|
841
|
+
# The settings are rendered by now: check them in full, templates no
|
|
842
|
+
# longer excused (a rendered value that still looks like one is refused).
|
|
843
|
+
rendered_errors = config_errors(config, allow_templates=False)
|
|
844
|
+
if rendered_errors:
|
|
845
|
+
return _refuse("; ".join(rendered_errors))
|
|
846
|
+
services = ctx.require_services()
|
|
847
|
+
source = config.source_step.strip()
|
|
848
|
+
artifacts = await services.fetch_run_artifacts(ctx.run_id)
|
|
849
|
+
selection = select_files(artifacts, source, config.path_template)
|
|
850
|
+
if selection.errors:
|
|
851
|
+
return _refuse("; ".join(selection.errors))
|
|
852
|
+
if not selection.files:
|
|
853
|
+
reason = f" ({'; '.join(selection.skipped)})" if selection.skipped else ""
|
|
854
|
+
return _refuse(f"step {source!r} has no text evidence in this run to commit{reason}")
|
|
855
|
+
|
|
856
|
+
try:
|
|
857
|
+
login = await resolve_secret_values(
|
|
858
|
+
ctx,
|
|
859
|
+
{
|
|
860
|
+
key: value
|
|
861
|
+
for key, value in (("username", config.username), ("password", config.password))
|
|
862
|
+
if value.strip()
|
|
863
|
+
},
|
|
864
|
+
source=HANDLER_ID,
|
|
865
|
+
)
|
|
866
|
+
except ValueError as exc:
|
|
867
|
+
return _refuse(str(exc))
|
|
868
|
+
|
|
869
|
+
files: list[StagedFile] = [StagedFile(MESSAGE_FILE, _message(config, ctx))]
|
|
870
|
+
manifest = []
|
|
871
|
+
for index, (path, content) in enumerate(sorted(selection.files.items())):
|
|
872
|
+
files.append(StagedFile(f"{FILES_DIR}/{index}", content))
|
|
873
|
+
manifest.append(f"{index} {path}")
|
|
874
|
+
files.append(StagedFile(MANIFEST_FILE, "\n".join(manifest) + "\n"))
|
|
875
|
+
if login:
|
|
876
|
+
files += [
|
|
877
|
+
StagedFile(USERNAME_FILE, login.get("username", "")),
|
|
878
|
+
StagedFile(PASSWORD_FILE, login.get("password", "")),
|
|
879
|
+
StagedFile(
|
|
880
|
+
ASKPASS_SCRIPT,
|
|
881
|
+
ASKPASS.format(username=USERNAME_FILE, password=PASSWORD_FILE),
|
|
882
|
+
mode=0o755,
|
|
883
|
+
),
|
|
884
|
+
]
|
|
885
|
+
if config.trusted_cas:
|
|
886
|
+
org_pem = await org_trusted_ca_pem(services)
|
|
887
|
+
if org_pem:
|
|
888
|
+
files.append(StagedFile(CA_FILE, combined_ca_pem(org_pem)))
|
|
889
|
+
|
|
890
|
+
timeout = step_container_timeout(ctx, config.timeout_seconds)
|
|
891
|
+
await report_timeout_cut(ctx, config.timeout_seconds, timeout)
|
|
892
|
+
script = build_script(
|
|
893
|
+
url=config.repository_url.strip(),
|
|
894
|
+
branch=config.branch.strip(),
|
|
895
|
+
create_branch=config.create_branch,
|
|
896
|
+
# The script stops git itself at the step's end, even if the worker is gone.
|
|
897
|
+
deadline=int(time.time()) + int(timeout),
|
|
898
|
+
login=bool(login),
|
|
899
|
+
ca_bundle=any(item.path == CA_FILE for item in files),
|
|
900
|
+
)
|
|
901
|
+
files.append(StagedFile(RUN_SCRIPT, script, mode=0o755))
|
|
902
|
+
identity = {
|
|
903
|
+
"GIT_AUTHOR_NAME": config.author_name.strip(),
|
|
904
|
+
"GIT_AUTHOR_EMAIL": config.author_email.strip(),
|
|
905
|
+
"GIT_COMMITTER_NAME": config.author_name.strip(),
|
|
906
|
+
"GIT_COMMITTER_EMAIL": config.author_email.strip(),
|
|
907
|
+
}
|
|
908
|
+
job = ContainerJob(
|
|
909
|
+
config={
|
|
910
|
+
**container_config_from(
|
|
911
|
+
{**ctx.config, "timeout_seconds": timeout},
|
|
912
|
+
image=config.image.strip(),
|
|
913
|
+
command=[f"exec sh {RUN_SCRIPT}"],
|
|
914
|
+
entrypoint="/bin/sh",
|
|
915
|
+
env=identity,
|
|
916
|
+
default_memory="512m",
|
|
917
|
+
),
|
|
918
|
+
"cache_image": config.cache_image,
|
|
919
|
+
},
|
|
920
|
+
files=files,
|
|
921
|
+
collect=[OUTPUT_DIR],
|
|
922
|
+
handler_id=self.handler_id,
|
|
923
|
+
)
|
|
924
|
+
outcome = await run_container_job(ctx, job)
|
|
925
|
+
if isinstance(outcome, HandlerResult):
|
|
926
|
+
return outcome
|
|
927
|
+
return self._result(config, selection, outcome)
|
|
928
|
+
|
|
929
|
+
def _result(
|
|
930
|
+
self, config: GitCommitConfig, selection: Selection, outcome: ContainerJobResult
|
|
931
|
+
) -> HandlerResult:
|
|
932
|
+
branch = config.branch.strip()
|
|
933
|
+
written = sorted(selection.files)
|
|
934
|
+
metrics = {
|
|
935
|
+
"exit_code": outcome.exit_code,
|
|
936
|
+
"duration_seconds": outcome.duration_seconds,
|
|
937
|
+
"files_written": len(written),
|
|
938
|
+
"image": outcome.image,
|
|
939
|
+
"image_digest": outcome.image_digest,
|
|
940
|
+
}
|
|
941
|
+
evidence = list(outcome.evidence)
|
|
942
|
+
if outcome.exit_code != 0:
|
|
943
|
+
return HandlerResult(
|
|
944
|
+
success=False,
|
|
945
|
+
summary="git commit failed",
|
|
946
|
+
error=failure_message(outcome, branch),
|
|
947
|
+
metrics=metrics,
|
|
948
|
+
evidence=evidence,
|
|
949
|
+
)
|
|
950
|
+
changed_flag = _decode(outcome, CHANGED_OUT).strip()
|
|
951
|
+
if changed_flag not in ("yes", "no"):
|
|
952
|
+
# Never guess: the push may or may not have happened.
|
|
953
|
+
return HandlerResult(
|
|
954
|
+
success=False,
|
|
955
|
+
summary="git commit result unknown",
|
|
956
|
+
error="the step's result could not be read from the container",
|
|
957
|
+
metrics=metrics,
|
|
958
|
+
evidence=evidence,
|
|
959
|
+
)
|
|
960
|
+
changed = changed_flag == "yes"
|
|
961
|
+
commit = _decode(outcome, COMMIT_OUT).strip()
|
|
962
|
+
changed_files = (
|
|
963
|
+
[path for path in _decode(outcome, CHANGED_FILES_OUT).split("\0") if path]
|
|
964
|
+
if changed
|
|
965
|
+
else []
|
|
966
|
+
)
|
|
967
|
+
if changed and (not commit or not changed_files):
|
|
968
|
+
# A push happened, but its report is incomplete: never guess.
|
|
969
|
+
return HandlerResult(
|
|
970
|
+
success=False,
|
|
971
|
+
summary="git commit result unknown",
|
|
972
|
+
error=(
|
|
973
|
+
"the push succeeded but the commit or the changed files could not be read "
|
|
974
|
+
"from the container"
|
|
975
|
+
),
|
|
976
|
+
metrics=metrics,
|
|
977
|
+
evidence=evidence,
|
|
978
|
+
)
|
|
979
|
+
metrics["files_changed"] = len(changed_files)
|
|
980
|
+
evidence.append(
|
|
981
|
+
{
|
|
982
|
+
"kind": "transport_meta",
|
|
983
|
+
"name": "git_commit",
|
|
984
|
+
"content_json": {
|
|
985
|
+
"repository_url": config.repository_url.strip(),
|
|
986
|
+
"branch": branch,
|
|
987
|
+
"changed": changed,
|
|
988
|
+
"commit": commit,
|
|
989
|
+
"files": written,
|
|
990
|
+
"changed_files": changed_files,
|
|
991
|
+
"skipped": selection.skipped,
|
|
992
|
+
},
|
|
993
|
+
}
|
|
994
|
+
)
|
|
995
|
+
short = commit[:12] if commit else "none"
|
|
996
|
+
if changed:
|
|
997
|
+
summary = f"Committed {len(changed_files)} changed file(s) to {branch} ({short})"
|
|
998
|
+
else:
|
|
999
|
+
summary = f"No changes: {len(written)} file(s) match {branch} ({short})"
|
|
1000
|
+
if selection.skipped:
|
|
1001
|
+
summary += f"; {len(selection.skipped)} capture(s) skipped"
|
|
1002
|
+
return HandlerResult(
|
|
1003
|
+
success=True,
|
|
1004
|
+
summary=summary,
|
|
1005
|
+
metrics=metrics,
|
|
1006
|
+
evidence=evidence,
|
|
1007
|
+
output={
|
|
1008
|
+
"changed": changed,
|
|
1009
|
+
"commit": commit,
|
|
1010
|
+
"branch": branch,
|
|
1011
|
+
"files": _capped(written),
|
|
1012
|
+
"changed_files": _capped(changed_files),
|
|
1013
|
+
"skipped": selection.skipped[:MAX_OUTPUT_PATHS],
|
|
1014
|
+
},
|
|
1015
|
+
)
|
|
1016
|
+
|
|
1017
|
+
|
|
1018
|
+
def _refuse(message: str) -> HandlerResult:
|
|
1019
|
+
return HandlerResult(success=False, error=message, summary="Cannot commit")
|