keep-github-workflows-active 2.0.0__py3-none-any.whl → 2.1.2__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.
- keep_github_workflows_active/__init__conf__.py +8 -1
- keep_github_workflows_active/cli.py +35 -14
- keep_github_workflows_active/doctest.env +1 -0
- keep_github_workflows_active/keep_github_workflow_active.py +291 -93
- keep_github_workflows_active/sanitization.py +379 -0
- {keep_github_workflows_active-2.0.0.dist-info → keep_github_workflows_active-2.1.2.dist-info}/METADATA +30 -12
- keep_github_workflows_active-2.1.2.dist-info/RECORD +14 -0
- {keep_github_workflows_active-2.0.0.dist-info → keep_github_workflows_active-2.1.2.dist-info}/WHEEL +1 -1
- keep_github_workflows_active-2.0.0.dist-info/RECORD +0 -12
- {keep_github_workflows_active-2.0.0.dist-info → keep_github_workflows_active-2.1.2.dist-info}/entry_points.txt +0 -0
- {keep_github_workflows_active-2.0.0.dist-info → keep_github_workflows_active-2.1.2.dist-info}/licenses/LICENSE +0 -0
|
@@ -24,7 +24,7 @@ name = "keep_github_workflows_active"
|
|
|
24
24
|
#: Human-readable summary shown in CLI help output.
|
|
25
25
|
title = "Template for python apps with registered cli commands"
|
|
26
26
|
#: Current release version pulled from ``pyproject.toml`` by automation.
|
|
27
|
-
version = "2.
|
|
27
|
+
version = "2.1.2"
|
|
28
28
|
#: Repository homepage presented to users.
|
|
29
29
|
homepage = "https://github.com/bitranox/keep_github_workflows_active"
|
|
30
30
|
#: Author attribution surfaced in CLI output.
|
|
@@ -34,6 +34,13 @@ author_email = "bitranox@gmail.com"
|
|
|
34
34
|
#: Console-script name published by the package.
|
|
35
35
|
shell_command = "keep-github-workflows-active"
|
|
36
36
|
|
|
37
|
+
#: Vendor identifier for lib_layered_config paths (macOS/Windows)
|
|
38
|
+
LAYEREDCONF_VENDOR: str = "bitranox"
|
|
39
|
+
#: Application display name for lib_layered_config paths (macOS/Windows)
|
|
40
|
+
LAYEREDCONF_APP: str = "Keep Github Workflows Active"
|
|
41
|
+
#: Configuration slug for lib_layered_config Linux paths and environment variables
|
|
42
|
+
LAYEREDCONF_SLUG: str = "keep-github-workflows-active"
|
|
43
|
+
|
|
37
44
|
|
|
38
45
|
def print_info() -> None:
|
|
39
46
|
"""Print the summarised metadata block used by the CLI ``info`` command.
|
|
@@ -40,7 +40,8 @@ behaviour remains consistent regardless of entry point.
|
|
|
40
40
|
from __future__ import annotations
|
|
41
41
|
|
|
42
42
|
from collections.abc import Sequence
|
|
43
|
-
from
|
|
43
|
+
from dataclasses import dataclass
|
|
44
|
+
from typing import Final, NamedTuple
|
|
44
45
|
|
|
45
46
|
import rich_click as click
|
|
46
47
|
|
|
@@ -51,13 +52,32 @@ from . import __init__conf__
|
|
|
51
52
|
from . import keep_github_workflow_active as keep_active
|
|
52
53
|
from .behaviors import emit_greeting, noop_main, raise_intentional_failure
|
|
53
54
|
|
|
55
|
+
|
|
56
|
+
# =============================================================================
|
|
57
|
+
# Dataclass for typed Click context object
|
|
58
|
+
# =============================================================================
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(slots=True)
|
|
62
|
+
class CliContextObject:
|
|
63
|
+
"""Typed context object for Click commands."""
|
|
64
|
+
|
|
65
|
+
traceback: bool = False
|
|
66
|
+
|
|
67
|
+
|
|
54
68
|
#: Shared Click context flags so help output stays consistent across commands.
|
|
55
|
-
CLICK_CONTEXT_SETTINGS = {"help_option_names": ["-h", "--help"]}
|
|
69
|
+
CLICK_CONTEXT_SETTINGS: dict[str, list[str]] = {"help_option_names": ["-h", "--help"]}
|
|
56
70
|
#: Character budget used when printing truncated tracebacks.
|
|
57
71
|
TRACEBACK_SUMMARY_LIMIT: Final[int] = 500
|
|
58
72
|
#: Character budget used when verbose tracebacks are enabled.
|
|
59
73
|
TRACEBACK_VERBOSE_LIMIT: Final[int] = 10_000
|
|
60
|
-
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class TracebackState(NamedTuple):
|
|
77
|
+
"""Typed state for traceback configuration."""
|
|
78
|
+
|
|
79
|
+
traceback_enabled: bool
|
|
80
|
+
force_color: bool
|
|
61
81
|
|
|
62
82
|
|
|
63
83
|
def _fallback_owner(owner: str | None) -> str:
|
|
@@ -108,7 +128,7 @@ def snapshot_traceback_state() -> TracebackState:
|
|
|
108
128
|
Returns
|
|
109
129
|
-------
|
|
110
130
|
TracebackState
|
|
111
|
-
|
|
131
|
+
NamedTuple with ``traceback_enabled`` and ``force_color`` fields.
|
|
112
132
|
|
|
113
133
|
Examples
|
|
114
134
|
--------
|
|
@@ -117,9 +137,9 @@ def snapshot_traceback_state() -> TracebackState:
|
|
|
117
137
|
True
|
|
118
138
|
"""
|
|
119
139
|
|
|
120
|
-
return (
|
|
121
|
-
bool(getattr(lib_cli_exit_tools.config, "traceback", False)),
|
|
122
|
-
bool(getattr(lib_cli_exit_tools.config, "traceback_force_color", False)),
|
|
140
|
+
return TracebackState(
|
|
141
|
+
traceback_enabled=bool(getattr(lib_cli_exit_tools.config, "traceback", False)),
|
|
142
|
+
force_color=bool(getattr(lib_cli_exit_tools.config, "traceback_force_color", False)),
|
|
123
143
|
)
|
|
124
144
|
|
|
125
145
|
|
|
@@ -129,7 +149,7 @@ def restore_traceback_state(state: TracebackState) -> None:
|
|
|
129
149
|
Parameters
|
|
130
150
|
----------
|
|
131
151
|
state:
|
|
132
|
-
|
|
152
|
+
NamedTuple returned by :func:`snapshot_traceback_state`.
|
|
133
153
|
|
|
134
154
|
Examples
|
|
135
155
|
--------
|
|
@@ -140,8 +160,8 @@ def restore_traceback_state(state: TracebackState) -> None:
|
|
|
140
160
|
True
|
|
141
161
|
"""
|
|
142
162
|
|
|
143
|
-
lib_cli_exit_tools.config.traceback =
|
|
144
|
-
lib_cli_exit_tools.config.traceback_force_color =
|
|
163
|
+
lib_cli_exit_tools.config.traceback = state.traceback_enabled
|
|
164
|
+
lib_cli_exit_tools.config.traceback_force_color = state.force_color
|
|
145
165
|
|
|
146
166
|
|
|
147
167
|
def _record_traceback_choice(ctx: click.Context, *, enabled: bool) -> None:
|
|
@@ -153,8 +173,8 @@ def _record_traceback_choice(ctx: click.Context, *, enabled: bool) -> None:
|
|
|
153
173
|
flags.
|
|
154
174
|
|
|
155
175
|
What
|
|
156
|
-
Ensures the context has a
|
|
157
|
-
|
|
176
|
+
Ensures the context has a typed CliContextObject and persists the boolean
|
|
177
|
+
in the ``traceback`` attribute.
|
|
158
178
|
|
|
159
179
|
Inputs
|
|
160
180
|
ctx:
|
|
@@ -166,8 +186,9 @@ def _record_traceback_choice(ctx: click.Context, *, enabled: bool) -> None:
|
|
|
166
186
|
Mutates ``ctx.obj``.
|
|
167
187
|
"""
|
|
168
188
|
|
|
169
|
-
ctx.
|
|
170
|
-
|
|
189
|
+
if ctx.obj is None or not isinstance(ctx.obj, CliContextObject):
|
|
190
|
+
ctx.obj = CliContextObject()
|
|
191
|
+
ctx.obj.traceback = enabled
|
|
171
192
|
|
|
172
193
|
|
|
173
194
|
def _announce_traceback_choice(enabled: bool) -> None:
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__EXAMPLE_KEY__=fallback
|
|
@@ -5,15 +5,214 @@ import logging
|
|
|
5
5
|
import os
|
|
6
6
|
import pathlib
|
|
7
7
|
import sys
|
|
8
|
+
from enum import IntEnum
|
|
9
|
+
from typing import Any
|
|
8
10
|
|
|
9
11
|
# EXT
|
|
10
12
|
import requests
|
|
13
|
+
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
|
14
|
+
|
|
15
|
+
# LOCAL
|
|
16
|
+
from . import sanitization
|
|
11
17
|
|
|
12
18
|
REQUEST_TIMEOUT_SECONDS = 30
|
|
13
19
|
|
|
14
20
|
logger = logging.getLogger(__name__)
|
|
15
21
|
|
|
16
22
|
|
|
23
|
+
# =============================================================================
|
|
24
|
+
# Enums for fixed string values
|
|
25
|
+
# =============================================================================
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class SkippedWorkflowType(IntEnum):
|
|
29
|
+
"""Workflow types that are skipped during enablement."""
|
|
30
|
+
|
|
31
|
+
PAGES_BUILD_DEPLOYMENT = 1
|
|
32
|
+
DEPENDABOT = 2
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
SKIPPED_WORKFLOW_PREFIXES: dict[SkippedWorkflowType, str] = {
|
|
36
|
+
SkippedWorkflowType.PAGES_BUILD_DEPLOYMENT: "pages-build-deployment",
|
|
37
|
+
SkippedWorkflowType.DEPENDABOT: "dependabot",
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# =============================================================================
|
|
42
|
+
# Pydantic models for GitHub API responses (external boundary)
|
|
43
|
+
# =============================================================================
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class GitHubRepository(BaseModel):
|
|
47
|
+
"""GitHub repository from API response."""
|
|
48
|
+
|
|
49
|
+
model_config = ConfigDict(extra="ignore")
|
|
50
|
+
name: str = ""
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class GitHubRepositoriesResponse(BaseModel):
|
|
54
|
+
"""List of repositories from GitHub API.
|
|
55
|
+
|
|
56
|
+
This model wraps the list response from the GitHub API.
|
|
57
|
+
Use model_validate() to parse raw JSON list responses.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
model_config = ConfigDict(extra="ignore")
|
|
61
|
+
repositories: list[GitHubRepository] = Field( # pyright: ignore[reportUnknownVariableType]
|
|
62
|
+
default_factory=list
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
@model_validator(mode="before")
|
|
66
|
+
@classmethod
|
|
67
|
+
def _wrap_list_response(cls, data: Any) -> dict[str, Any]: # noqa: ANN401
|
|
68
|
+
"""Wrap list responses into the expected dict structure."""
|
|
69
|
+
if isinstance(data, list):
|
|
70
|
+
return {"repositories": data}
|
|
71
|
+
if isinstance(data, dict):
|
|
72
|
+
return dict(data) # pyright: ignore[reportUnknownArgumentType]
|
|
73
|
+
return {"repositories": []}
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class GitHubWorkflow(BaseModel):
|
|
77
|
+
"""GitHub workflow from API response."""
|
|
78
|
+
|
|
79
|
+
model_config = ConfigDict(extra="ignore")
|
|
80
|
+
path: str = ""
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def filename(self) -> str:
|
|
84
|
+
"""Extract workflow filename from path."""
|
|
85
|
+
return pathlib.Path(self.path).name
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class GitHubWorkflowsResponse(BaseModel):
|
|
89
|
+
"""Workflows response from GitHub API.
|
|
90
|
+
|
|
91
|
+
Uses Pydantic's built-in validation to parse the GitHub API response.
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
model_config = ConfigDict(extra="ignore")
|
|
95
|
+
workflows: list[GitHubWorkflow] = Field( # pyright: ignore[reportUnknownVariableType]
|
|
96
|
+
default_factory=list
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class GitHubWorkflowRun(BaseModel):
|
|
101
|
+
"""GitHub workflow run from API response."""
|
|
102
|
+
|
|
103
|
+
model_config = ConfigDict(extra="ignore")
|
|
104
|
+
id: int = 0
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class GitHubWorkflowRunsResponse(BaseModel):
|
|
108
|
+
"""Workflow runs response from GitHub API.
|
|
109
|
+
|
|
110
|
+
Uses Pydantic's built-in validation to parse the GitHub API response.
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
model_config = ConfigDict(extra="ignore")
|
|
114
|
+
workflow_runs: list[GitHubWorkflowRun] = Field( # pyright: ignore[reportUnknownVariableType]
|
|
115
|
+
default_factory=list
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class GitHubErrorResponse(BaseModel):
|
|
120
|
+
"""GitHub API error response.
|
|
121
|
+
|
|
122
|
+
Uses Pydantic's built-in validation to parse error responses.
|
|
123
|
+
"""
|
|
124
|
+
|
|
125
|
+
model_config = ConfigDict(extra="ignore")
|
|
126
|
+
message: str = "Error"
|
|
127
|
+
|
|
128
|
+
@classmethod
|
|
129
|
+
def from_response(cls, response: requests.Response | None) -> "GitHubErrorResponse":
|
|
130
|
+
"""Parse error from response, handling various failure modes."""
|
|
131
|
+
if response is None:
|
|
132
|
+
return cls()
|
|
133
|
+
try:
|
|
134
|
+
return cls.model_validate(response.json())
|
|
135
|
+
except (ValueError, AttributeError):
|
|
136
|
+
return cls(message=response.text or response.reason or "Error")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class PaginationLink(BaseModel):
|
|
140
|
+
"""Single pagination link from GitHub API response headers.
|
|
141
|
+
|
|
142
|
+
Represents a single link entry from the Link header used for pagination.
|
|
143
|
+
"""
|
|
144
|
+
|
|
145
|
+
model_config = ConfigDict(extra="ignore")
|
|
146
|
+
url: str = ""
|
|
147
|
+
|
|
148
|
+
@classmethod
|
|
149
|
+
def from_link_dict(cls, link_data: dict[str, str] | None) -> "PaginationLink | None":
|
|
150
|
+
"""Parse pagination link from requests library link dict.
|
|
151
|
+
|
|
152
|
+
Parameters
|
|
153
|
+
----------
|
|
154
|
+
link_data:
|
|
155
|
+
Dictionary from requests.Response.links containing 'url' key.
|
|
156
|
+
|
|
157
|
+
Returns
|
|
158
|
+
-------
|
|
159
|
+
PaginationLink | None
|
|
160
|
+
Parsed link model or None if no valid data.
|
|
161
|
+
"""
|
|
162
|
+
if link_data is None:
|
|
163
|
+
return None
|
|
164
|
+
url = link_data.get("url", "")
|
|
165
|
+
if not url:
|
|
166
|
+
return None
|
|
167
|
+
return cls(url=url)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
# =============================================================================
|
|
171
|
+
# Pydantic model for internal configuration
|
|
172
|
+
# =============================================================================
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class EnvConfig(BaseModel):
|
|
176
|
+
"""Environment configuration values parsed from .env file.
|
|
177
|
+
|
|
178
|
+
Uses Pydantic's built-in validation with extra='allow' to capture
|
|
179
|
+
arbitrary key-value pairs from .env files. Access values via attribute
|
|
180
|
+
access (e.g., config.KEY) or the get() method.
|
|
181
|
+
"""
|
|
182
|
+
|
|
183
|
+
model_config = ConfigDict(extra="allow", frozen=True)
|
|
184
|
+
|
|
185
|
+
def __getattr__(self, key: str) -> str | None:
|
|
186
|
+
"""Retrieve configuration value by attribute access.
|
|
187
|
+
|
|
188
|
+
Examples
|
|
189
|
+
--------
|
|
190
|
+
>>> config = EnvConfig.model_validate({"FOO": "bar"})
|
|
191
|
+
>>> config.FOO
|
|
192
|
+
'bar'
|
|
193
|
+
>>> config.MISSING is None
|
|
194
|
+
True
|
|
195
|
+
"""
|
|
196
|
+
extra = self.model_extra or {}
|
|
197
|
+
value = extra.get(key)
|
|
198
|
+
return str(value) if value is not None else None
|
|
199
|
+
|
|
200
|
+
def get_value(self, key: str) -> str | None:
|
|
201
|
+
"""Retrieve configuration value by key (explicit method).
|
|
202
|
+
|
|
203
|
+
Parameters
|
|
204
|
+
----------
|
|
205
|
+
key:
|
|
206
|
+
The configuration key to look up.
|
|
207
|
+
|
|
208
|
+
Returns
|
|
209
|
+
-------
|
|
210
|
+
str | None
|
|
211
|
+
The configuration value as a string, or None if not found.
|
|
212
|
+
"""
|
|
213
|
+
return getattr(self, key)
|
|
214
|
+
|
|
215
|
+
|
|
17
216
|
def _candidate_env_files() -> list[pathlib.Path]:
|
|
18
217
|
"""Return existing ``.env`` files to inspect in priority order.
|
|
19
218
|
|
|
@@ -35,7 +234,7 @@ def _candidate_env_files() -> list[pathlib.Path]:
|
|
|
35
234
|
"""
|
|
36
235
|
|
|
37
236
|
script_dir = pathlib.Path(__file__).resolve().parent
|
|
38
|
-
repo_root = script_dir.parent
|
|
237
|
+
repo_root = script_dir.parent.parent
|
|
39
238
|
candidates: list[pathlib.Path] = []
|
|
40
239
|
|
|
41
240
|
override = os.environ.get("KEEP_GITHUB_WORKFLOWS_ACTIVE_DOTENV_PATH")
|
|
@@ -61,7 +260,7 @@ def _candidate_env_files() -> list[pathlib.Path]:
|
|
|
61
260
|
return existing_files
|
|
62
261
|
|
|
63
262
|
|
|
64
|
-
def _read_env_file(path: pathlib.Path) ->
|
|
263
|
+
def _read_env_file(path: pathlib.Path) -> EnvConfig:
|
|
65
264
|
"""Parse ``key=value`` pairs from a ``.env`` file.
|
|
66
265
|
|
|
67
266
|
Parameters
|
|
@@ -71,8 +270,8 @@ def _read_env_file(path: pathlib.Path) -> dict[str, str]:
|
|
|
71
270
|
|
|
72
271
|
Returns
|
|
73
272
|
-------
|
|
74
|
-
|
|
75
|
-
|
|
273
|
+
EnvConfig
|
|
274
|
+
Pydantic model containing parsed configuration values.
|
|
76
275
|
|
|
77
276
|
Examples
|
|
78
277
|
--------
|
|
@@ -81,11 +280,11 @@ def _read_env_file(path: pathlib.Path) -> dict[str, str]:
|
|
|
81
280
|
... _ = tmp.write("FOO=bar\\n# comment\\nBAZ = qux\\n")
|
|
82
281
|
... _ = tmp.flush()
|
|
83
282
|
... parsed = _read_env_file(pathlib.Path(tmp.name))
|
|
84
|
-
>>> parsed ==
|
|
283
|
+
>>> parsed.FOO == "bar" and parsed.BAZ == "qux"
|
|
85
284
|
True
|
|
86
285
|
"""
|
|
87
286
|
|
|
88
|
-
|
|
287
|
+
parsed_values: dict[str, str] = {}
|
|
89
288
|
with path.open(encoding="utf-8") as stream:
|
|
90
289
|
for raw_line in stream:
|
|
91
290
|
stripped = raw_line.strip()
|
|
@@ -94,8 +293,8 @@ def _read_env_file(path: pathlib.Path) -> dict[str, str]:
|
|
|
94
293
|
key, separator, remainder = stripped.partition("=")
|
|
95
294
|
if not separator:
|
|
96
295
|
continue
|
|
97
|
-
|
|
98
|
-
return
|
|
296
|
+
parsed_values[key.strip()] = remainder.strip().strip('"').strip("'")
|
|
297
|
+
return EnvConfig.model_validate(parsed_values)
|
|
99
298
|
|
|
100
299
|
|
|
101
300
|
def _lookup_config_value(key: str) -> str:
|
|
@@ -143,7 +342,7 @@ def _lookup_config_value(key: str) -> str:
|
|
|
143
342
|
|
|
144
343
|
for env_file in _candidate_env_files():
|
|
145
344
|
config = _read_env_file(env_file)
|
|
146
|
-
file_value = config.
|
|
345
|
+
file_value = config.get_value(key)
|
|
147
346
|
if file_value:
|
|
148
347
|
return file_value
|
|
149
348
|
|
|
@@ -162,12 +361,8 @@ def enable_all_workflows(owner: str, github_token: str) -> None:
|
|
|
162
361
|
... except RuntimeError:
|
|
163
362
|
... my_owner = my_github_token = None
|
|
164
363
|
>>> if my_owner and my_github_token:
|
|
165
|
-
...
|
|
166
|
-
...
|
|
167
|
-
... stdout = StringIO()
|
|
168
|
-
... with redirect_stdout(stdout):
|
|
169
|
-
... enable_all_workflows(owner=my_owner, github_token=my_github_token)
|
|
170
|
-
... assert stdout.getvalue()
|
|
364
|
+
... enable_all_workflows(owner=my_owner, github_token=my_github_token) # doctest: +ELLIPSIS
|
|
365
|
+
Activating ...
|
|
171
366
|
|
|
172
367
|
"""
|
|
173
368
|
print(f"Activating and maintaining all workflows for owner {owner}:")
|
|
@@ -192,12 +387,9 @@ def delete_old_workflow_runs(owner: str, github_token: str, number_of_workflow_r
|
|
|
192
387
|
... except RuntimeError:
|
|
193
388
|
... owner = token = None
|
|
194
389
|
>>> if owner and token:
|
|
195
|
-
...
|
|
196
|
-
...
|
|
197
|
-
|
|
198
|
-
... with redirect_stdout(stdout):
|
|
199
|
-
... delete_old_workflow_runs(owner=owner, github_token=token, number_of_workflow_runs_to_keep=50)
|
|
200
|
-
... assert stdout.getvalue()
|
|
390
|
+
... delete_old_workflow_runs(owner=owner, github_token=token, number_of_workflow_runs_to_keep=50) # doctest: +ELLIPSIS
|
|
391
|
+
Removing ...
|
|
392
|
+
|
|
201
393
|
|
|
202
394
|
"""
|
|
203
395
|
print(
|
|
@@ -208,7 +400,11 @@ def delete_old_workflow_runs(owner: str, github_token: str, number_of_workflow_r
|
|
|
208
400
|
workflow_run_ids = get_workflow_runs(owner=owner, repository=repository, github_token=github_token)
|
|
209
401
|
workflow_run_ids_sorted = sorted(workflow_run_ids, reverse=True)
|
|
210
402
|
workflow_run_ids_to_delete = workflow_run_ids_sorted[number_of_workflow_runs_to_keep:]
|
|
211
|
-
logger.info(
|
|
403
|
+
logger.info(
|
|
404
|
+
sanitization.sanitize_message(
|
|
405
|
+
f"repository: {repository}, {len(workflow_run_ids)} workflow runs found, {len(workflow_run_ids_to_delete)} to delete."
|
|
406
|
+
)
|
|
407
|
+
)
|
|
212
408
|
for run_id_to_delete in workflow_run_ids_to_delete:
|
|
213
409
|
print(f"remove workflow run {repository}/{run_id_to_delete}")
|
|
214
410
|
delete_workflow_run(owner=owner, repository=repository, github_token=github_token, run_id_to_delete=run_id_to_delete)
|
|
@@ -231,13 +427,6 @@ def get_owner() -> str:
|
|
|
231
427
|
------
|
|
232
428
|
RuntimeError
|
|
233
429
|
If the value is missing from both the environment and ``.env`` files.
|
|
234
|
-
|
|
235
|
-
Examples
|
|
236
|
-
--------
|
|
237
|
-
>>> os.environ["SECRET_GITHUB_OWNER"] = "demo-user"
|
|
238
|
-
>>> get_owner()
|
|
239
|
-
'demo-user'
|
|
240
|
-
>>> _ = os.environ.pop("SECRET_GITHUB_OWNER")
|
|
241
430
|
"""
|
|
242
431
|
|
|
243
432
|
return _lookup_config_value("SECRET_GITHUB_OWNER")
|
|
@@ -259,18 +448,32 @@ def get_github_token() -> str:
|
|
|
259
448
|
------
|
|
260
449
|
RuntimeError
|
|
261
450
|
If the token is missing everywhere we check.
|
|
262
|
-
|
|
263
|
-
Examples
|
|
264
|
-
--------
|
|
265
|
-
>>> os.environ["SECRET_GITHUB_TOKEN"] = "abc123"
|
|
266
|
-
>>> get_github_token()
|
|
267
|
-
'abc123'
|
|
268
|
-
>>> _ = os.environ.pop("SECRET_GITHUB_TOKEN")
|
|
269
451
|
"""
|
|
270
452
|
|
|
271
453
|
return _lookup_config_value("SECRET_GITHUB_TOKEN")
|
|
272
454
|
|
|
273
455
|
|
|
456
|
+
def _get_next_page_url(response: requests.Response) -> str | None:
|
|
457
|
+
"""Extract next page URL from GitHub API pagination links.
|
|
458
|
+
|
|
459
|
+
Parses the Link header from the GitHub API response and returns
|
|
460
|
+
the 'next' page URL if present.
|
|
461
|
+
|
|
462
|
+
Parameters
|
|
463
|
+
----------
|
|
464
|
+
response:
|
|
465
|
+
HTTP response from GitHub API.
|
|
466
|
+
|
|
467
|
+
Returns
|
|
468
|
+
-------
|
|
469
|
+
str | None
|
|
470
|
+
URL for the next page, or None if no more pages.
|
|
471
|
+
"""
|
|
472
|
+
link_dict = response.links.get("next")
|
|
473
|
+
link = PaginationLink.from_link_dict(link_dict)
|
|
474
|
+
return link.url if link else None
|
|
475
|
+
|
|
476
|
+
|
|
274
477
|
def get_repositories(owner: str, github_token: str) -> list[str]:
|
|
275
478
|
"""
|
|
276
479
|
Fetch all repositories for a given GitHub user, handling pagination and setting the page size to 100.
|
|
@@ -290,27 +493,25 @@ def get_repositories(owner: str, github_token: str) -> list[str]:
|
|
|
290
493
|
|
|
291
494
|
"""
|
|
292
495
|
repositories: list[str] = []
|
|
293
|
-
url = f"https://api.github.com/users/{owner}/repos?per_page=100"
|
|
496
|
+
url: str | None = f"https://api.github.com/users/{owner}/repos?per_page=100"
|
|
294
497
|
headers = {"Authorization": f"Bearer {github_token}", "Accept": "application/vnd.github.v3+json"}
|
|
295
498
|
|
|
296
499
|
while url:
|
|
297
500
|
try:
|
|
298
501
|
response = requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
|
|
299
|
-
response.raise_for_status()
|
|
300
|
-
|
|
301
|
-
repositories.extend(
|
|
302
|
-
|
|
303
|
-
# Get the URL for the next page from the response headers, if present
|
|
304
|
-
url = response.links.get("next", {}).get("url", None)
|
|
502
|
+
response.raise_for_status()
|
|
503
|
+
parsed = GitHubRepositoriesResponse.model_validate(response.json())
|
|
504
|
+
repositories.extend(repo.name for repo in parsed.repositories)
|
|
505
|
+
url = _get_next_page_url(response)
|
|
305
506
|
|
|
306
507
|
except requests.exceptions.HTTPError as exc:
|
|
307
|
-
|
|
308
|
-
result = f"ERROR reading repositories for user {owner}: {
|
|
309
|
-
logger.error(result)
|
|
508
|
+
error = GitHubErrorResponse.from_response(exc.response)
|
|
509
|
+
result = f"ERROR reading repositories for user {owner}: {error.message}"
|
|
510
|
+
logger.error(sanitization.sanitize_message(result))
|
|
310
511
|
raise RuntimeError(result) from exc
|
|
311
512
|
|
|
312
513
|
result = f"Found {len(repositories)} repositories for user {owner}"
|
|
313
|
-
logger.info(result)
|
|
514
|
+
logger.info(sanitization.sanitize_message(result))
|
|
314
515
|
return repositories
|
|
315
516
|
|
|
316
517
|
|
|
@@ -337,31 +538,29 @@ def get_workflows(owner: str, repository: str, github_token: str) -> list[str]:
|
|
|
337
538
|
|
|
338
539
|
"""
|
|
339
540
|
workflows: list[str] = []
|
|
340
|
-
url = f"https://api.github.com/repos/{owner}/{repository}/actions/workflows?per_page=100"
|
|
541
|
+
url: str | None = f"https://api.github.com/repos/{owner}/{repository}/actions/workflows?per_page=100"
|
|
341
542
|
headers = {"Authorization": f"Bearer {github_token}", "Accept": "application/vnd.github.v3+json"}
|
|
342
543
|
|
|
343
544
|
while url:
|
|
344
545
|
try:
|
|
345
546
|
response = requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
|
|
346
|
-
response.raise_for_status()
|
|
347
|
-
|
|
348
|
-
workflows.extend(
|
|
349
|
-
|
|
350
|
-
# Get the URL for the next page from the response headers, if present
|
|
351
|
-
url = response.links.get("next", {}).get("url", None)
|
|
547
|
+
response.raise_for_status()
|
|
548
|
+
parsed = GitHubWorkflowsResponse.model_validate(response.json())
|
|
549
|
+
workflows.extend(workflow.filename for workflow in parsed.workflows)
|
|
550
|
+
url = _get_next_page_url(response)
|
|
352
551
|
|
|
353
552
|
except requests.exceptions.HTTPError as exc:
|
|
354
|
-
|
|
355
|
-
result = f"ERROR reading workflows for user: {owner}, repository: {repository}, {
|
|
356
|
-
logger.error(result)
|
|
553
|
+
error = GitHubErrorResponse.from_response(exc.response)
|
|
554
|
+
result = f"ERROR reading workflows for user: {owner}, repository: {repository}, {error.message}"
|
|
555
|
+
logger.error(sanitization.sanitize_message(result))
|
|
357
556
|
raise RuntimeError(result) from exc
|
|
358
557
|
|
|
359
558
|
result = f"Found {len(workflows)} workflows for user: {owner}, repository: {repository}"
|
|
360
|
-
logger.info(result)
|
|
559
|
+
logger.info(sanitization.sanitize_message(result))
|
|
361
560
|
return workflows
|
|
362
561
|
|
|
363
562
|
|
|
364
|
-
def get_workflow_runs(owner: str, repository: str, github_token: str) -> list[
|
|
563
|
+
def get_workflow_runs(owner: str, repository: str, github_token: str) -> list[int]:
|
|
365
564
|
"""
|
|
366
565
|
Fetch all workflow runs for a GitHub repository using the GitHub API v3, handling pagination.
|
|
367
566
|
|
|
@@ -382,35 +581,33 @@ def get_workflow_runs(owner: str, repository: str, github_token: str) -> list[st
|
|
|
382
581
|
|
|
383
582
|
|
|
384
583
|
"""
|
|
385
|
-
|
|
386
|
-
url = f"https://api.github.com/repos/{owner}/{repository}/actions/runs?per_page=100"
|
|
584
|
+
url: str | None = f"https://api.github.com/repos/{owner}/{repository}/actions/runs?per_page=100"
|
|
387
585
|
headers = {"Authorization": f"Bearer {github_token}", "Accept": "application/vnd.github.v3+json"}
|
|
388
586
|
|
|
389
|
-
workflow_run_ids: list[
|
|
587
|
+
workflow_run_ids: list[int] = []
|
|
390
588
|
while url:
|
|
391
589
|
try:
|
|
392
590
|
response = requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
|
|
393
|
-
response.raise_for_status()
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
workflow_run_ids.extend([run["id"] for run in data.get("workflow_runs", [])])
|
|
398
|
-
|
|
399
|
-
# Check for the 'next' page link
|
|
400
|
-
url = response.links.get("next", {}).get("url", None)
|
|
591
|
+
response.raise_for_status()
|
|
592
|
+
parsed = GitHubWorkflowRunsResponse.model_validate(response.json())
|
|
593
|
+
workflow_run_ids.extend(run.id for run in parsed.workflow_runs)
|
|
594
|
+
url = _get_next_page_url(response)
|
|
401
595
|
|
|
402
596
|
except requests.exceptions.HTTPError as exc:
|
|
403
|
-
|
|
404
|
-
result = f"ERROR reading workflow runs for user: {owner}, repository: {repository}, {
|
|
405
|
-
logger.error(result)
|
|
597
|
+
error = GitHubErrorResponse.from_response(exc.response)
|
|
598
|
+
result = f"ERROR reading workflow runs for user: {owner}, repository: {repository}, {error.message}"
|
|
599
|
+
logger.error(sanitization.sanitize_message(result))
|
|
406
600
|
raise RuntimeError(result) from exc
|
|
407
601
|
|
|
408
602
|
result = f"Found {len(workflow_run_ids)} workflow runs for user: {owner}, repository: {repository}"
|
|
409
|
-
logger.info(result)
|
|
603
|
+
logger.info(sanitization.sanitize_message(result))
|
|
410
604
|
return workflow_run_ids
|
|
411
605
|
|
|
412
606
|
|
|
413
|
-
|
|
607
|
+
HTTP_NO_CONTENT = 204
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def delete_workflow_run(owner: str, repository: str, github_token: str, run_id_to_delete: int) -> None:
|
|
414
611
|
"""
|
|
415
612
|
Delete a specified workflow run for a GitHub repository.
|
|
416
613
|
|
|
@@ -426,17 +623,24 @@ def delete_workflow_run(owner: str, repository: str, github_token: str, run_id_t
|
|
|
426
623
|
try:
|
|
427
624
|
response = requests.delete(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
|
|
428
625
|
|
|
429
|
-
if response.status_code ==
|
|
626
|
+
if response.status_code == HTTP_NO_CONTENT:
|
|
430
627
|
result = f"Deleted workflow run ID: {run_id_to_delete} for user: {owner}, repository: {repository}"
|
|
431
|
-
logger.info(result)
|
|
628
|
+
logger.info(sanitization.sanitize_message(result))
|
|
432
629
|
|
|
433
630
|
except requests.exceptions.RequestException as exc:
|
|
434
|
-
# For HTTP errors, requests will raise a RequestException. Here we catch all errors derived from RequestException
|
|
435
631
|
result_error_message = f"ERROR deleting workflow run ID: {run_id_to_delete} for user: {owner}, repository: {repository}: {exc}"
|
|
436
|
-
logger.error(result_error_message)
|
|
632
|
+
logger.error(sanitization.sanitize_message(result_error_message))
|
|
437
633
|
raise RuntimeError(result_error_message) from exc
|
|
438
634
|
|
|
439
635
|
|
|
636
|
+
def _is_skipped_workflow(workflow_filename: str) -> SkippedWorkflowType | None:
|
|
637
|
+
"""Check if workflow should be skipped and return the reason."""
|
|
638
|
+
for skip_type, prefix in SKIPPED_WORKFLOW_PREFIXES.items():
|
|
639
|
+
if workflow_filename.startswith(prefix):
|
|
640
|
+
return skip_type
|
|
641
|
+
return None
|
|
642
|
+
|
|
643
|
+
|
|
440
644
|
def enable_workflow(owner: str, repository: str, workflow_filename: str, github_token: str) -> str:
|
|
441
645
|
"""
|
|
442
646
|
Enable a workflow in a GitHub repository using the GitHub API.
|
|
@@ -469,33 +673,27 @@ def enable_workflow(owner: str, repository: str, workflow_filename: str, github_
|
|
|
469
673
|
|
|
470
674
|
"""
|
|
471
675
|
url = f"https://api.github.com/repos/{owner}/{repository}/actions/workflows/{workflow_filename}/enable"
|
|
472
|
-
|
|
473
676
|
headers = {"Accept": "application/vnd.github.v3+json", "Authorization": f"Bearer {github_token}"}
|
|
474
677
|
|
|
475
678
|
response: requests.Response | None = None
|
|
476
679
|
try:
|
|
477
|
-
|
|
680
|
+
skip_reason = _is_skipped_workflow(workflow_filename)
|
|
681
|
+
if skip_reason == SkippedWorkflowType.PAGES_BUILD_DEPLOYMENT:
|
|
478
682
|
result = f"Repository {repository}, workflow {workflow_filename} skipped - those can not be enabled"
|
|
479
|
-
elif
|
|
683
|
+
elif skip_reason == SkippedWorkflowType.DEPENDABOT:
|
|
480
684
|
result = f"Repository {repository}, workflow {workflow_filename} skipped - managed by Dependabot"
|
|
481
685
|
else:
|
|
482
686
|
response = requests.put(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
|
|
483
|
-
response.raise_for_status()
|
|
687
|
+
response.raise_for_status()
|
|
484
688
|
result = f"Enabled repository {repository}, workflow {workflow_filename}"
|
|
485
|
-
logger.info(result)
|
|
689
|
+
logger.info(sanitization.sanitize_message(result))
|
|
486
690
|
return result
|
|
487
691
|
|
|
488
692
|
except requests.exceptions.HTTPError as exc:
|
|
489
693
|
resp = exc.response if exc.response is not None else response
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
except ValueError:
|
|
494
|
-
error_message = resp.text or resp.reason or "Error"
|
|
495
|
-
else:
|
|
496
|
-
error_message = str(exc)
|
|
497
|
-
result = f"ERROR enabling repository {repository}, workflow {workflow_filename}: {error_message}"
|
|
498
|
-
logger.error(result)
|
|
694
|
+
error = GitHubErrorResponse.from_response(resp)
|
|
695
|
+
result = f"ERROR enabling repository {repository}, workflow {workflow_filename}: {error.message}"
|
|
696
|
+
logger.error(sanitization.sanitize_message(result))
|
|
499
697
|
raise RuntimeError(result) from exc
|
|
500
698
|
|
|
501
699
|
|
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
"""Security helpers for sanitizing sensitive data from logs and outputs.
|
|
2
|
+
|
|
3
|
+
Purpose
|
|
4
|
+
-------
|
|
5
|
+
Prevent credential leakage by redacting sensitive values from headers, messages,
|
|
6
|
+
and data structures before they reach logging systems. All helpers are pure
|
|
7
|
+
functions returning sanitized copies without mutating inputs.
|
|
8
|
+
|
|
9
|
+
Contents
|
|
10
|
+
--------
|
|
11
|
+
* :func:`sanitize_headers` – redact Authorization and authentication headers.
|
|
12
|
+
* :func:`sanitize_message` – redact token-like patterns from text.
|
|
13
|
+
* :func:`sanitize_dict` – recursively sanitize dictionary values.
|
|
14
|
+
* :func:`sanitize_for_logging` – convenience wrapper for common logging scenarios.
|
|
15
|
+
|
|
16
|
+
System Role
|
|
17
|
+
-----------
|
|
18
|
+
Acts as the security boundary for all logging operations involving external API
|
|
19
|
+
interactions. Import these helpers wherever sensitive data might be logged to
|
|
20
|
+
ensure credentials never leak into log files or monitoring systems.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import re
|
|
26
|
+
from collections.abc import Mapping as MappingABC
|
|
27
|
+
from typing import Any, Mapping
|
|
28
|
+
|
|
29
|
+
#: HTTP header names that contain sensitive authentication data.
|
|
30
|
+
SENSITIVE_HEADERS = frozenset(
|
|
31
|
+
[
|
|
32
|
+
"authorization",
|
|
33
|
+
"x-api-key",
|
|
34
|
+
"api-key",
|
|
35
|
+
"x-auth-token",
|
|
36
|
+
"auth-token",
|
|
37
|
+
"cookie",
|
|
38
|
+
"set-cookie",
|
|
39
|
+
]
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
#: Dictionary keys that typically contain sensitive values.
|
|
43
|
+
SENSITIVE_KEYS = frozenset(
|
|
44
|
+
[
|
|
45
|
+
"authorization",
|
|
46
|
+
"api_key",
|
|
47
|
+
"api-key",
|
|
48
|
+
"apikey",
|
|
49
|
+
"token",
|
|
50
|
+
"auth_token",
|
|
51
|
+
"auth-token",
|
|
52
|
+
"access_token",
|
|
53
|
+
"access-token",
|
|
54
|
+
"secret",
|
|
55
|
+
"password",
|
|
56
|
+
"passwd",
|
|
57
|
+
"pwd",
|
|
58
|
+
"credential",
|
|
59
|
+
"credentials",
|
|
60
|
+
]
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
#: Replacement text for redacted values.
|
|
64
|
+
REDACTED_PLACEHOLDER = "[REDACTED]"
|
|
65
|
+
|
|
66
|
+
#: Pattern matching token-like strings:
|
|
67
|
+
#: - GitHub tokens (ghp_, gho_, ghs_, etc. followed by alphanumerics)
|
|
68
|
+
#: - Long hex strings (40+ chars)
|
|
69
|
+
#: - Base64-like sequences (40+ chars)
|
|
70
|
+
TOKEN_PATTERN = re.compile(
|
|
71
|
+
r"\b(gh[a-z]_[A-Za-z0-9]{36,}|[a-f0-9]{40,}|[A-Za-z0-9+/]{40,}={0,2})\b",
|
|
72
|
+
re.IGNORECASE,
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _is_sensitive_header(name: str) -> bool:
|
|
77
|
+
"""Return True when header name contains authentication data.
|
|
78
|
+
|
|
79
|
+
Parameters
|
|
80
|
+
----------
|
|
81
|
+
name:
|
|
82
|
+
HTTP header name to check.
|
|
83
|
+
|
|
84
|
+
Returns
|
|
85
|
+
-------
|
|
86
|
+
bool
|
|
87
|
+
True when the header should be redacted.
|
|
88
|
+
|
|
89
|
+
Examples
|
|
90
|
+
--------
|
|
91
|
+
>>> _is_sensitive_header("Authorization")
|
|
92
|
+
True
|
|
93
|
+
>>> _is_sensitive_header("Content-Type")
|
|
94
|
+
False
|
|
95
|
+
>>> _is_sensitive_header("X-API-Key")
|
|
96
|
+
True
|
|
97
|
+
"""
|
|
98
|
+
|
|
99
|
+
return name.lower() in SENSITIVE_HEADERS
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _redact_value() -> str:
|
|
103
|
+
"""Return the standard redaction placeholder.
|
|
104
|
+
|
|
105
|
+
Returns
|
|
106
|
+
-------
|
|
107
|
+
str
|
|
108
|
+
Placeholder text replacing sensitive values.
|
|
109
|
+
|
|
110
|
+
Examples
|
|
111
|
+
--------
|
|
112
|
+
>>> _redact_value()
|
|
113
|
+
'[REDACTED]'
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
return REDACTED_PLACEHOLDER
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _sanitize_header_value(name: str, value: str) -> str:
|
|
120
|
+
"""Return sanitized header value or placeholder when sensitive.
|
|
121
|
+
|
|
122
|
+
Parameters
|
|
123
|
+
----------
|
|
124
|
+
name:
|
|
125
|
+
HTTP header name.
|
|
126
|
+
value:
|
|
127
|
+
Header value to potentially redact.
|
|
128
|
+
|
|
129
|
+
Returns
|
|
130
|
+
-------
|
|
131
|
+
str
|
|
132
|
+
Original value when safe, placeholder when sensitive.
|
|
133
|
+
|
|
134
|
+
Examples
|
|
135
|
+
--------
|
|
136
|
+
>>> _sanitize_header_value("Content-Type", "application/json")
|
|
137
|
+
'application/json'
|
|
138
|
+
>>> _sanitize_header_value("Authorization", "Bearer ghp_secret123")
|
|
139
|
+
'[REDACTED]'
|
|
140
|
+
"""
|
|
141
|
+
|
|
142
|
+
return _redact_value() if _is_sensitive_header(name) else value
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def sanitize_headers(headers: Mapping[str, str]) -> dict[str, str]:
|
|
146
|
+
"""Return copy of headers with authentication values redacted.
|
|
147
|
+
|
|
148
|
+
Why
|
|
149
|
+
HTTP headers often contain tokens or API keys. Logging raw headers
|
|
150
|
+
would leak credentials into monitoring systems and log files.
|
|
151
|
+
|
|
152
|
+
What
|
|
153
|
+
Creates a shallow copy with sensitive header values replaced by
|
|
154
|
+
:data:`REDACTED_PLACEHOLDER`. Recognized headers include Authorization,
|
|
155
|
+
X-API-Key, Cookie, and others defined in :data:`SENSITIVE_HEADERS`.
|
|
156
|
+
|
|
157
|
+
Parameters
|
|
158
|
+
----------
|
|
159
|
+
headers:
|
|
160
|
+
HTTP headers dictionary potentially containing secrets.
|
|
161
|
+
|
|
162
|
+
Returns
|
|
163
|
+
-------
|
|
164
|
+
dict[str, str]
|
|
165
|
+
Sanitized copy safe for logging.
|
|
166
|
+
|
|
167
|
+
Examples
|
|
168
|
+
--------
|
|
169
|
+
>>> headers = {"Authorization": "Bearer ghp_abc123", "Accept": "application/json"}
|
|
170
|
+
>>> sanitized = sanitize_headers(headers)
|
|
171
|
+
>>> sanitized["Authorization"]
|
|
172
|
+
'[REDACTED]'
|
|
173
|
+
>>> sanitized["Accept"]
|
|
174
|
+
'application/json'
|
|
175
|
+
>>> headers["Authorization"] # Original unchanged
|
|
176
|
+
'Bearer ghp_abc123'
|
|
177
|
+
"""
|
|
178
|
+
|
|
179
|
+
return {name: _sanitize_header_value(name, value) for name, value in headers.items()}
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _redact_token_match(match: re.Match[str]) -> str:
|
|
183
|
+
"""Return redaction placeholder for regex token matches.
|
|
184
|
+
|
|
185
|
+
Parameters
|
|
186
|
+
----------
|
|
187
|
+
match:
|
|
188
|
+
Regex match object containing a token-like string.
|
|
189
|
+
|
|
190
|
+
Returns
|
|
191
|
+
-------
|
|
192
|
+
str
|
|
193
|
+
Redaction placeholder.
|
|
194
|
+
"""
|
|
195
|
+
|
|
196
|
+
return _redact_value()
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def sanitize_message(text: str) -> str:
|
|
200
|
+
"""Return message with token-like patterns redacted.
|
|
201
|
+
|
|
202
|
+
Why
|
|
203
|
+
Error messages and log statements may inadvertently include tokens from
|
|
204
|
+
URLs, JSON payloads, or API responses. This helper scrubs patterns that
|
|
205
|
+
resemble authentication tokens.
|
|
206
|
+
|
|
207
|
+
What
|
|
208
|
+
Uses :data:`TOKEN_PATTERN` to detect long hexadecimal or base64-like
|
|
209
|
+
sequences and replaces them with :data:`REDACTED_PLACEHOLDER`.
|
|
210
|
+
|
|
211
|
+
Parameters
|
|
212
|
+
----------
|
|
213
|
+
text:
|
|
214
|
+
Message string potentially containing tokens.
|
|
215
|
+
|
|
216
|
+
Returns
|
|
217
|
+
-------
|
|
218
|
+
str
|
|
219
|
+
Sanitized message safe for logging.
|
|
220
|
+
|
|
221
|
+
Examples
|
|
222
|
+
--------
|
|
223
|
+
>>> msg = "Request failed: token=ghp_1234567890abcdefABCDEF1234567890abcdefAB"
|
|
224
|
+
>>> sanitize_message(msg)
|
|
225
|
+
'Request failed: token=[REDACTED]'
|
|
226
|
+
>>> sanitize_message("Normal log message")
|
|
227
|
+
'Normal log message'
|
|
228
|
+
"""
|
|
229
|
+
|
|
230
|
+
return TOKEN_PATTERN.sub(_redact_token_match, text)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _is_sensitive_key(name: str) -> bool:
|
|
234
|
+
"""Return True when dictionary key contains sensitive data.
|
|
235
|
+
|
|
236
|
+
Parameters
|
|
237
|
+
----------
|
|
238
|
+
name:
|
|
239
|
+
Dictionary key name to check.
|
|
240
|
+
|
|
241
|
+
Returns
|
|
242
|
+
-------
|
|
243
|
+
bool
|
|
244
|
+
True when the key should be redacted.
|
|
245
|
+
|
|
246
|
+
Examples
|
|
247
|
+
--------
|
|
248
|
+
>>> _is_sensitive_key("token")
|
|
249
|
+
True
|
|
250
|
+
>>> _is_sensitive_key("api_key")
|
|
251
|
+
True
|
|
252
|
+
>>> _is_sensitive_key("count")
|
|
253
|
+
False
|
|
254
|
+
"""
|
|
255
|
+
|
|
256
|
+
return name.lower() in SENSITIVE_KEYS or name.lower() in SENSITIVE_HEADERS
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _sanitize_dict_value(key: str, value: Any) -> Any: # noqa: ANN401
|
|
260
|
+
"""Return sanitized value for dictionary entry.
|
|
261
|
+
|
|
262
|
+
Parameters
|
|
263
|
+
----------
|
|
264
|
+
key:
|
|
265
|
+
Dictionary key name.
|
|
266
|
+
value:
|
|
267
|
+
Value to potentially sanitize.
|
|
268
|
+
|
|
269
|
+
Returns
|
|
270
|
+
-------
|
|
271
|
+
Any
|
|
272
|
+
Sanitized value (redacted if key is sensitive, recursively sanitized
|
|
273
|
+
if dict, original otherwise).
|
|
274
|
+
|
|
275
|
+
Examples
|
|
276
|
+
--------
|
|
277
|
+
>>> _sanitize_dict_value("api_key", "secret123")
|
|
278
|
+
'[REDACTED]'
|
|
279
|
+
>>> _sanitize_dict_value("count", 42)
|
|
280
|
+
42
|
|
281
|
+
"""
|
|
282
|
+
|
|
283
|
+
if _is_sensitive_key(key):
|
|
284
|
+
return _redact_value()
|
|
285
|
+
if isinstance(value, (dict, MappingABC)):
|
|
286
|
+
# Type narrowing: we know value is Mapping at this point
|
|
287
|
+
return sanitize_dict(value) # type: ignore[arg-type]
|
|
288
|
+
if isinstance(value, str):
|
|
289
|
+
return sanitize_message(value)
|
|
290
|
+
return value
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def sanitize_dict(data: Mapping[str, Any]) -> dict[str, Any]:
|
|
294
|
+
"""Return deep copy of dictionary with sensitive values redacted.
|
|
295
|
+
|
|
296
|
+
Why
|
|
297
|
+
Structured logging often includes entire request/response dictionaries.
|
|
298
|
+
Recursively sanitizing nested structures ensures credentials never leak.
|
|
299
|
+
|
|
300
|
+
What
|
|
301
|
+
Creates a deep copy where sensitive keys (matching
|
|
302
|
+
:data:`SENSITIVE_HEADERS`) are redacted, nested dicts are recursively
|
|
303
|
+
processed, and string values are scrubbed for token patterns.
|
|
304
|
+
|
|
305
|
+
Parameters
|
|
306
|
+
----------
|
|
307
|
+
data:
|
|
308
|
+
Dictionary potentially containing sensitive data.
|
|
309
|
+
|
|
310
|
+
Returns
|
|
311
|
+
-------
|
|
312
|
+
dict[str, Any]
|
|
313
|
+
Sanitized copy safe for logging.
|
|
314
|
+
|
|
315
|
+
Examples
|
|
316
|
+
--------
|
|
317
|
+
>>> data = {"user": "alice", "token": "ghp_secret", "meta": {"api_key": "xyz"}}
|
|
318
|
+
>>> sanitized = sanitize_dict(data)
|
|
319
|
+
>>> sanitized["user"]
|
|
320
|
+
'alice'
|
|
321
|
+
>>> sanitized["token"]
|
|
322
|
+
'[REDACTED]'
|
|
323
|
+
>>> sanitized["meta"]["api_key"]
|
|
324
|
+
'[REDACTED]'
|
|
325
|
+
"""
|
|
326
|
+
|
|
327
|
+
return {key: _sanitize_dict_value(key, value) for key, value in data.items()}
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def sanitize_for_logging(value: Any) -> Any: # noqa: ANN401
|
|
331
|
+
"""Return sanitized representation suitable for logging.
|
|
332
|
+
|
|
333
|
+
Why
|
|
334
|
+
Logging calls may receive various types (dicts, strings, objects).
|
|
335
|
+
This convenience function dispatches to the appropriate sanitizer.
|
|
336
|
+
|
|
337
|
+
What
|
|
338
|
+
Detects the input type and applies the relevant sanitization strategy:
|
|
339
|
+
dicts are recursively sanitized, strings are scrubbed for tokens,
|
|
340
|
+
other types pass through unchanged.
|
|
341
|
+
|
|
342
|
+
Parameters
|
|
343
|
+
----------
|
|
344
|
+
value:
|
|
345
|
+
Value to sanitize for logging.
|
|
346
|
+
|
|
347
|
+
Returns
|
|
348
|
+
-------
|
|
349
|
+
Any
|
|
350
|
+
Sanitized representation safe for logs.
|
|
351
|
+
|
|
352
|
+
Examples
|
|
353
|
+
--------
|
|
354
|
+
>>> sanitize_for_logging({"Authorization": "Bearer secret"})
|
|
355
|
+
{'Authorization': '[REDACTED]'}
|
|
356
|
+
>>> sanitize_for_logging("Token: ghp_1234567890abcdefABCDEF1234567890abcdefAB")
|
|
357
|
+
'Token: [REDACTED]'
|
|
358
|
+
>>> sanitize_for_logging(42)
|
|
359
|
+
42
|
|
360
|
+
"""
|
|
361
|
+
|
|
362
|
+
if isinstance(value, (dict, MappingABC)):
|
|
363
|
+
# Type narrowing: we know value is Mapping at this point
|
|
364
|
+
return sanitize_dict(value) # type: ignore[arg-type]
|
|
365
|
+
if isinstance(value, str):
|
|
366
|
+
return sanitize_message(value)
|
|
367
|
+
return value
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
__all__ = [
|
|
371
|
+
"SENSITIVE_HEADERS",
|
|
372
|
+
"SENSITIVE_KEYS",
|
|
373
|
+
"REDACTED_PLACEHOLDER",
|
|
374
|
+
"TOKEN_PATTERN",
|
|
375
|
+
"sanitize_headers",
|
|
376
|
+
"sanitize_message",
|
|
377
|
+
"sanitize_dict",
|
|
378
|
+
"sanitize_for_logging",
|
|
379
|
+
]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: keep_github_workflows_active
|
|
3
|
-
Version: 2.
|
|
3
|
+
Version: 2.1.2
|
|
4
4
|
Summary: Template for python apps with registered cli commands
|
|
5
5
|
Project-URL: Homepage, https://github.com/bitranox/keep_github_workflows_active
|
|
6
6
|
Project-URL: Repository, https://github.com/bitranox/keep_github_workflows_active.git
|
|
@@ -16,20 +16,22 @@ Classifier: Programming Language :: Python :: 3
|
|
|
16
16
|
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
17
|
Classifier: Typing :: Typed
|
|
18
18
|
Requires-Python: >=3.13
|
|
19
|
-
Requires-Dist: lib-cli-exit-tools>=2.
|
|
20
|
-
Requires-Dist:
|
|
21
|
-
Requires-Dist:
|
|
19
|
+
Requires-Dist: lib-cli-exit-tools>=2.2.2
|
|
20
|
+
Requires-Dist: pydantic>=2.12.5
|
|
21
|
+
Requires-Dist: requests>=2.32.5
|
|
22
|
+
Requires-Dist: rich-click>=1.9.4
|
|
22
23
|
Provides-Extra: dev
|
|
23
|
-
Requires-Dist: bandit>=1.
|
|
24
|
+
Requires-Dist: bandit>=1.9.2; extra == 'dev'
|
|
24
25
|
Requires-Dist: build>=1.3.0; extra == 'dev'
|
|
25
|
-
Requires-Dist: codecov-cli>=11.2.
|
|
26
|
-
Requires-Dist: import-linter>=2.
|
|
27
|
-
Requires-Dist: pip-audit>=2.
|
|
28
|
-
Requires-Dist: pyright>=1.1.
|
|
26
|
+
Requires-Dist: codecov-cli>=11.2.6; extra == 'dev'
|
|
27
|
+
Requires-Dist: import-linter>=2.9; extra == 'dev'
|
|
28
|
+
Requires-Dist: pip-audit>=2.10.0; extra == 'dev'
|
|
29
|
+
Requires-Dist: pyright>=1.1.407; extra == 'dev'
|
|
29
30
|
Requires-Dist: pytest-cov>=7.0.0; extra == 'dev'
|
|
30
|
-
Requires-Dist: pytest>=
|
|
31
|
-
Requires-Dist:
|
|
32
|
-
Requires-Dist:
|
|
31
|
+
Requires-Dist: pytest>=9.0.2; extra == 'dev'
|
|
32
|
+
Requires-Dist: rtoml>=0.13.0; extra == 'dev'
|
|
33
|
+
Requires-Dist: ruff>=0.14.9; extra == 'dev'
|
|
34
|
+
Requires-Dist: textual>=6.9.0; extra == 'dev'
|
|
33
35
|
Requires-Dist: twine>=6.2.0; extra == 'dev'
|
|
34
36
|
Description-Content-Type: text/markdown
|
|
35
37
|
|
|
@@ -46,6 +48,9 @@ Description-Content-Type: text/markdown
|
|
|
46
48
|
[](https://codecov.io/gh/bitranox/keep_github_workflows_active)
|
|
47
49
|
[](https://qlty.sh/gh/bitranox/projects/keep_github_workflows_active)
|
|
48
50
|
[](https://snyk.io/test/github/bitranox/keep_github_workflows_active)
|
|
51
|
+
[](https://github.com/PyCQA/bandit)
|
|
52
|
+
|
|
53
|
+
> **CI cadence:** The GitHub Actions CI workflow runs automatically every Monday at 07:00 UTC, in addition to push and pull request triggers.
|
|
49
54
|
|
|
50
55
|
|
|
51
56
|
## Overview
|
|
@@ -182,6 +187,18 @@ kgwa.print_info()
|
|
|
182
187
|
```
|
|
183
188
|
|
|
184
189
|
|
|
190
|
+
## Security
|
|
191
|
+
|
|
192
|
+
All logging operations sanitize sensitive data before output to prevent credential
|
|
193
|
+
leakage. The automation redacts:
|
|
194
|
+
|
|
195
|
+
- GitHub personal access tokens (ghp_*, gho_*, etc.)
|
|
196
|
+
- Authorization headers and API keys
|
|
197
|
+
- Token-like patterns in error messages
|
|
198
|
+
|
|
199
|
+
For complete security documentation including incident response procedures, see
|
|
200
|
+
[SECURITY.md](docs/systemdesign/SECURITY.md).
|
|
201
|
+
|
|
185
202
|
## Further documentation
|
|
186
203
|
|
|
187
204
|
- [Install Guide](INSTALL.md)
|
|
@@ -189,4 +206,5 @@ kgwa.print_info()
|
|
|
189
206
|
- [Contributor Guide](CONTRIBUTING.md)
|
|
190
207
|
- [Changelog](CHANGELOG.md)
|
|
191
208
|
- [Module Reference](docs/systemdesign/module_reference.md)
|
|
209
|
+
- [Security Documentation](docs/systemdesign/SECURITY.md)
|
|
192
210
|
- [License](LICENSE)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
keep_github_workflows_active/__init__.py,sha256=tAEJPhRW07E84IzHijcwAf-iu8fhAf3TsvBUQqGz-fY,399
|
|
2
|
+
keep_github_workflows_active/__init__conf__.py,sha256=z--69zJ0x_4XPKzhXs6IYdod3J6uW2aMW2HG2cBL8Hc,2562
|
|
3
|
+
keep_github_workflows_active/__main__.py,sha256=79coRxvGs07uGBSdbw_HpcIv_rqogXvoEkv3lNEEIjE,3552
|
|
4
|
+
keep_github_workflows_active/behaviors.py,sha256=PYDhp_ubXhLud2IVFLIJKylStu36W4Qm7E_daT2dOAM,3741
|
|
5
|
+
keep_github_workflows_active/cli.py,sha256=KLLeRvnKuaE45GgX8GS-Aa5l7GGaKE7QjX7KtTV2ZUc,19007
|
|
6
|
+
keep_github_workflows_active/doctest.env,sha256=WmDSq0QN1PFXpP4jq7JW_Kz-k5PT5uS8KzLrAEmJNC8,25
|
|
7
|
+
keep_github_workflows_active/keep_github_workflow_active.py,sha256=4eETTyn-8sHCTtC_4qD3yjNbPwTMD31WpDMLroQ3V94,24685
|
|
8
|
+
keep_github_workflows_active/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
keep_github_workflows_active/sanitization.py,sha256=zyPybyYLBWd__nITF8nyrubA3NJWXjyGkznw-4kJtyA,9801
|
|
10
|
+
keep_github_workflows_active-2.1.2.dist-info/METADATA,sha256=qvvLfnuQCBapGmumj3EMCsT_UuFAFAc6GaDOPN_GYwk,9489
|
|
11
|
+
keep_github_workflows_active-2.1.2.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
|
|
12
|
+
keep_github_workflows_active-2.1.2.dist-info/entry_points.txt,sha256=6B8ytwKR2VIAj6IXUYhF957dlfulwTPPLR39RBXwCM0,156
|
|
13
|
+
keep_github_workflows_active-2.1.2.dist-info/licenses/LICENSE,sha256=6s9SL2InRrwynPjJYiER7ONHBshbGj_yC5EBzfo7l9I,1072
|
|
14
|
+
keep_github_workflows_active-2.1.2.dist-info/RECORD,,
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
keep_github_workflows_active/__init__.py,sha256=tAEJPhRW07E84IzHijcwAf-iu8fhAf3TsvBUQqGz-fY,399
|
|
2
|
-
keep_github_workflows_active/__init__conf__.py,sha256=MBKRESh1V_6C9eYtEqTB52Xx1CAmSAqDFnQBVo7tYYE,2193
|
|
3
|
-
keep_github_workflows_active/__main__.py,sha256=79coRxvGs07uGBSdbw_HpcIv_rqogXvoEkv3lNEEIjE,3552
|
|
4
|
-
keep_github_workflows_active/behaviors.py,sha256=PYDhp_ubXhLud2IVFLIJKylStu36W4Qm7E_daT2dOAM,3741
|
|
5
|
-
keep_github_workflows_active/cli.py,sha256=h-xK6wwbyonIgH0Nhb_eQ_lrws9MGea78AhSbaEW2HI,18355
|
|
6
|
-
keep_github_workflows_active/keep_github_workflow_active.py,sha256=25cEcqfOiedeM443RrqeLc0PcZoSyiAjrcuYkGRmfbk,18809
|
|
7
|
-
keep_github_workflows_active/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
-
keep_github_workflows_active-2.0.0.dist-info/METADATA,sha256=O1tr_D9rF_NG30WfeIIUzlBZeKfuvZ-2JKAmGlti9VQ,8712
|
|
9
|
-
keep_github_workflows_active-2.0.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
10
|
-
keep_github_workflows_active-2.0.0.dist-info/entry_points.txt,sha256=6B8ytwKR2VIAj6IXUYhF957dlfulwTPPLR39RBXwCM0,156
|
|
11
|
-
keep_github_workflows_active-2.0.0.dist-info/licenses/LICENSE,sha256=6s9SL2InRrwynPjJYiER7ONHBshbGj_yC5EBzfo7l9I,1072
|
|
12
|
-
keep_github_workflows_active-2.0.0.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|