fix(security): close the 32 open CodeQL alerts

Critical #60/#61 untrusted checkout: publish-containers.yml prepare runs for workflow_run only when the triggering run succeeded, was a push and came from this repository; build and merge need prepare, so the guard covers both checkouts. Mark stable commit triggers only on push of v* tags, schedule and workflow_dispatch are unchanged. Medium #55/#56: update-flake-lock.yml pins nix-installer-action v23 and update-flake-lock v29 to commit SHAs. High: secret_service_token returns only the token and raises SecretServiceUnavailable with the same reasons, _forge_access builds the token/reason pair (#62); jinja2 select_autoescape for html/htm/xml only, scaffolding output byte-identical (#29); chmod 0o755 to 0o700 for owner-run scripts in ink.py and 7 test sites; exact URL equality in a mirror probe test. Error #33: raise unittest.SkipTest from exc. Notes: empty-except to contextlib.suppress, one import form per module, unused variable, commented-out code, assertNotIn.

| 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| fix/codeql-alerts | 28 files +92/-81 | 90 % | 3 % | – | – | 100 % | 87 | ✅ 90/5, tokens and velocity <= 100, security 100 % |

Evidence: tests/unit + tests/integration 880 passed, 574 subtests; 2 test_publish_integration failures are identical on a clone without these changes (global tag.gpgsign, sandbox blocks gpg). ruff and actionlint clean, MEDUSA 100 % critical 0 (1 accepted keyword false positive). Operator choice 7589a6f1 (swarm), operator review dcc2f461.
Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-30 20:19:21 +00:00
1 parent f529139db5
commit 0f6583ca48
28 files changed
+92 -81

No files matched your search

+1 -1
View File
@@ -10,7 +10,7 @@ on:
jobs: jobs:
prepare: prepare:
if: ${{ github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success' }} if: ${{ github.event_name != 'workflow_run' || (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'push' && github.event.workflow_run.head_repository.full_name == github.repository) }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions: permissions:
+2 -2
View File
@@ -21,10 +21,10 @@ jobs:
uses: actions/checkout@v7 uses: actions/checkout@v7
- name: Install Nix - name: Install Nix
uses: DeterminateSystems/nix-installer-action@v23 uses: DeterminateSystems/nix-installer-action@3138316df39ed29be04236d7ffc686fa525866aa # v23
- name: Update flake.lock and open a pull request - name: Update flake.lock and open a pull request
uses: DeterminateSystems/update-flake-lock@v29 uses: DeterminateSystems/update-flake-lock@da03c0f078bc4b2c37ee4f7e072d34bf8f188bb3 # v29
with: with:
pr-title: "chore(deps): update flake.lock" pr-title: "chore(deps): update flake.lock"
pr-labels: | pr-labels: |
+24 -12
View File
@@ -50,17 +50,22 @@ def _cache_path(owner: str, name: str) -> str:
return os.path.join(base, "pkgmgr", "forge", owner, f"{name}.json") return os.path.join(base, "pkgmgr", "forge", owner, f"{name}.json")
def secret_service_token() -> tuple[str | None, str | None]: class SecretServiceUnavailable(Exception):
""" pass
Read the GitHub token from the Secret Service without unlocking it.
def secret_service_token() -> str:
"""
Returns: Returns:
(token, None), or (None, why no token is available). The GitHub token from the Secret Service, read without unlocking it.
Raises:
SecretServiceUnavailable: names why no token is available.
""" """
try: try:
import secretstorage import secretstorage
except ImportError: except ImportError as exc:
return None, "secretstorage not installed" raise SecretServiceUnavailable("secretstorage not installed") from exc
key = build_keyring_key("github", GITHUB_HOST, None) key = build_keyring_key("github", GITHUB_HOST, None)
try: try:
connection = secretstorage.dbus_init() connection = secretstorage.dbus_init()
@@ -72,14 +77,21 @@ def secret_service_token() -> tuple[str | None, str | None]:
) )
unlocked = [item for item in items if not item.is_locked()] unlocked = [item for item in items if not item.is_locked()]
if not items: if not items:
return None, "no GitHub token in the Secret Service" raise SecretServiceUnavailable("no GitHub token in the Secret Service")
if not unlocked: if not unlocked:
return None, "Secret Service locked" raise SecretServiceUnavailable("Secret Service locked")
return unlocked[0].get_secret().decode(), None return unlocked[0].get_secret().decode()
finally: finally:
connection.close() connection.close()
except (secretstorage.exceptions.SecretStorageException, OSError) as exc: except (secretstorage.exceptions.SecretStorageException, OSError) as exc:
return None, f"Secret Service unavailable: {exc}" raise SecretServiceUnavailable(f"Secret Service unavailable: {exc}") from exc
def _forge_access() -> tuple[str | None, str | None]:
try:
return secret_service_token(), None
except SecretServiceUnavailable as exc:
return None, str(exc)
@contextmanager @contextmanager
@@ -315,7 +327,7 @@ def branch_tree(
""" """
known = list(dict.fromkeys(os.path.realpath(d) for d in repo_dirs)) known = list(dict.fromkeys(os.path.realpath(d) for d in repo_dirs))
orphans = [d for d in _shared_owners(worktrees_root) if d not in known] orphans = [d for d in _shared_owners(worktrees_root) if d not in known]
token, reason = secret_service_token() token, reason = _forge_access()
host_ns = gc.host_pid_namespace() host_ns = gc.host_pid_namespace()
containers = gc.list_compose_containers() containers = gc.list_compose_containers()
data = { data = {
@@ -357,7 +369,7 @@ def refresh_tree_entry(repo_root: str) -> None:
if not os.path.isfile(path) or not gc.host_pid_namespace(): if not os.path.isfile(path) or not gc.host_pid_namespace():
return return
root = os.path.realpath(repo_root) root = os.path.realpath(repo_root)
token, reason = secret_service_token() token, reason = _forge_access()
fresh = _scan(root, True, token, reason, gc.list_compose_containers(), True) fresh = _scan(root, True, token, reason, gc.list_compose_containers(), True)
with _locked(path): with _locked(path):
with open(path, encoding="utf-8") as fh: with open(path, encoding="utf-8") as fh:
-1
View File
@@ -161,7 +161,6 @@ class InstallationPipeline:
else: else:
repo.pop("command", None) repo.pop("command", None)
state = new_state
return return
if attempted: if attempted:
@@ -7,8 +7,13 @@ from typing import Any
from pkgmgr.core.git.queries import get_repo_root from pkgmgr.core.git.queries import get_repo_root
try: try:
from jinja2 import Environment, FileSystemLoader, StrictUndefined from jinja2 import (
except ImportError as exc: # pragma: no cover Environment,
FileSystemLoader,
StrictUndefined,
select_autoescape,
)
except ImportError as exc: # pragma: no cover
Environment = None # type: ignore Environment = None # type: ignore
FileSystemLoader = None # type: ignore FileSystemLoader = None # type: ignore
StrictUndefined = None # type: ignore StrictUndefined = None # type: ignore
@@ -41,7 +46,11 @@ class TemplateRenderer:
env = Environment( env = Environment(
loader=FileSystemLoader(self.templates_dir), loader=FileSystemLoader(self.templates_dir),
undefined=StrictUndefined, undefined=StrictUndefined,
autoescape=False, autoescape=select_autoescape(
enabled_extensions=("html", "htm", "xml"),
default_for_string=False,
default=False,
),
keep_trailing_newline=True, keep_trailing_newline=True,
) )
+1 -1
View File
@@ -68,7 +68,7 @@ def create_ink(
# Mark local repo scripts as executable if needed # Mark local repo scripts as executable if needed
try: try:
if os.path.realpath(command).startswith(os.path.realpath(repo_dir)): if os.path.realpath(command).startswith(os.path.realpath(repo_dir)):
os.chmod(command, 0o755) os.chmod(command, 0o700)
except OSError as e: except OSError as e:
if not quiet: if not quiet:
print(f"Failed to set permissions on '{command}': {e}") print(f"Failed to set permissions on '{command}': {e}")
@@ -1,6 +1,7 @@
# src/pkgmgr/core/remote_provisioning/providers/github.py # src/pkgmgr/core/remote_provisioning/providers/github.py
from __future__ import annotations from __future__ import annotations
import contextlib
from typing import Any from typing import Any
from ..http.client import HttpClient from ..http.client import HttpClient
@@ -103,7 +104,7 @@ class GitHubProvider(RemoteProvider):
user_url = f"{api}/user/repos" user_url = f"{api}/user/repos"
# Try org first, then fall back to user creation. # Try org first, then fall back to user creation.
try: with contextlib.suppress(HttpError):
resp = self._http.request_json( resp = self._http.request_json(
"POST", org_url, headers=self._headers(token), payload=payload "POST", org_url, headers=self._headers(token), payload=payload
) )
@@ -114,8 +115,6 @@ class GitHubProvider(RemoteProvider):
message="Repository created (org).", message="Repository created (org).",
url=str(html_url) if html_url else None, url=str(html_url) if html_url else None,
) )
except HttpError:
pass
resp = self._http.request_json( resp = self._http.request_json(
"POST", user_url, headers=self._headers(token), payload=payload "POST", user_url, headers=self._headers(token), payload=payload
+2 -3
View File
@@ -1,5 +1,6 @@
from __future__ import annotations from __future__ import annotations
import contextlib
import json import json
import re import re
import shutil import shutil
@@ -127,7 +128,7 @@ def get_installed_nix_profile_version(*candidates: str) -> InstalledVersion | No
# Preferred: JSON output # Preferred: JSON output
rc, out, _ = _run_nix(["nix", "profile", "list", "--json"]) rc, out, _ = _run_nix(["nix", "profile", "list", "--json"])
if rc == 0 and out.strip(): if rc == 0 and out.strip():
try: with contextlib.suppress(json.JSONDecodeError, AttributeError):
data = json.loads(out) data = json.loads(out)
elements = data.get("elements") or data.get("items") or {} elements = data.get("elements") or data.get("items") or {}
if isinstance(elements, dict): if isinstance(elements, dict):
@@ -145,8 +146,6 @@ def get_installed_nix_profile_version(*candidates: str) -> InstalledVersion | No
guess = _extract_version_from_store_path(sp) guess = _extract_version_from_store_path(sp)
if guess: if guess:
return InstalledVersion(name=name, version=guess) return InstalledVersion(name=name, version=guess)
except (json.JSONDecodeError, AttributeError):
pass
# Fallback: text mode # Fallback: text mode
rc, out, _ = _run_nix(["nix", "profile", "list"]) rc, out, _ = _run_nix(["nix", "profile", "list"])
+2 -3
View File
@@ -1,6 +1,7 @@
# src/pkgmgr/core/version/source.py # src/pkgmgr/core/version/source.py
from __future__ import annotations from __future__ import annotations
import contextlib
import os import os
import re import re
@@ -259,14 +260,12 @@ def read_ansible_galaxy_version(repo_dir: str) -> str | None:
""" """
galaxy_yml = os.path.join(repo_dir, "galaxy.yml") galaxy_yml = os.path.join(repo_dir, "galaxy.yml")
if os.path.isfile(galaxy_yml): if os.path.isfile(galaxy_yml):
try: with contextlib.suppress(OSError, UnicodeDecodeError, yaml.YAMLError):
with open(galaxy_yml, encoding="utf-8") as f: with open(galaxy_yml, encoding="utf-8") as f:
data = yaml.safe_load(f) or {} data = yaml.safe_load(f) or {}
version = data.get("version") version = data.get("version")
if isinstance(version, str) and version.strip(): if isinstance(version, str) and version.strip():
return version.strip() return version.strip()
except (OSError, UnicodeDecodeError, yaml.YAMLError):
pass
meta_yml = os.path.join(repo_dir, "meta", "main.yml") meta_yml = os.path.join(repo_dir, "meta", "main.yml")
if os.path.isfile(meta_yml): if os.path.isfile(meta_yml):
@@ -116,7 +116,7 @@ class TestBranchCleanupLocal(unittest.TestCase):
docker = os.path.join(self.bin, "docker") docker = os.path.join(self.bin, "docker")
with open(docker, "w", encoding="utf-8") as fh: with open(docker, "w", encoding="utf-8") as fh:
fh.write(FAILING_DOCKER.format(python=sys.executable)) fh.write(FAILING_DOCKER.format(python=sys.executable))
os.chmod(docker, 0o755) os.chmod(docker, 0o700)
self.docker_log = os.path.join(self.root, "docker.log") self.docker_log = os.path.join(self.root, "docker.log")
def tearDown(self) -> None: def tearDown(self) -> None:
@@ -159,7 +159,7 @@ class TestBranchCleanupLocal(unittest.TestCase):
patch.object(gc_forge, "TokenResolver") as resolver, patch.object(gc_forge, "TokenResolver") as resolver,
patch.object(gc_forge, "HttpClient") as http, patch.object(gc_forge, "HttpClient") as http,
patch.object( patch.object(
tree, "secret_service_token", return_value=(None, "test") tree, "_forge_access", return_value=(None, "test")
) as secret, ) as secret,
): ):
resolver.return_value.get_token.side_effect = NoCredentialsError("none") resolver.return_value.get_token.side_effect = NoCredentialsError("none")
@@ -1688,7 +1688,7 @@ class TestBranchCleanupLocal(unittest.TestCase):
path = os.path.join(hooks, name) path = os.path.join(hooks, name)
with open(path, "w", encoding="utf-8") as fh: with open(path, "w", encoding="utf-8") as fh:
fh.write(MARKING_HOOK.format(marker=marker)) fh.write(MARKING_HOOK.format(marker=marker))
os.chmod(path, 0o755) os.chmod(path, 0o700)
run = self._cleanup("local", apply=True) run = self._cleanup("local", apply=True)
+1 -1
View File
@@ -534,7 +534,7 @@ class TestBranchGc(GcFixture, unittest.TestCase):
hook = os.path.join(self.repo, ".git", "hooks", "reference-transaction") hook = os.path.join(self.repo, ".git", "hooks", "reference-transaction")
with open(hook, "w") as fh: with open(hook, "w") as fh:
fh.write(f"#!/bin/sh\ntouch {marker}\n") fh.write(f"#!/bin/sh\ntouch {marker}\n")
os.chmod(hook, 0o755) os.chmod(hook, 0o700)
plan = self._plan(host_ns=True, cwds={}) plan = self._plan(host_ns=True, cwds={})
item = self._items(plan)["merged"] item = self._items(plan)["merged"]
+4 -4
View File
@@ -110,7 +110,7 @@ class TestBranchTree(unittest.TestCase):
patch.object(gc, "_process_cwds", return_value={}), patch.object(gc, "_process_cwds", return_value={}),
patch.object( patch.object(
tree, tree,
"secret_service_token", "_forge_access",
return_value=(None, "Secret Service locked"), return_value=(None, "Secret Service locked"),
), ),
] ]
@@ -389,7 +389,7 @@ class TestBranchTree(unittest.TestCase):
open_heads={}, open_heads={},
) )
with ( with (
patch.object(tree, "secret_service_token", return_value=("t0ken", None)), patch.object(tree, "_forge_access", return_value=("t0ken", None)),
patch.object(tree, "facts_with_token", return_value=facts) as live, patch.object(tree, "facts_with_token", return_value=facts) as live,
): ):
first = self._by_branch(self._entry()) first = self._by_branch(self._entry())
@@ -408,7 +408,7 @@ class TestBranchTree(unittest.TestCase):
(False, "Secret Service locked"), (False, "Secret Service locked"),
) )
self.assertEqual(data["repos"][0]["forge"], "cached") self.assertEqual(data["repos"][0]["forge"], "cached")
with patch.object(tree, "secret_service_token", return_value=("t0ken", None)): with patch.object(tree, "_forge_access", return_value=("t0ken", None)):
self.assertTrue(json.loads(self._tree())["delete_ready"]) self.assertTrue(json.loads(self._tree())["delete_ready"])
def test_an_unwritable_cache_keeps_the_scan_and_names_it(self) -> None: def test_an_unwritable_cache_keeps_the_scan_and_names_it(self) -> None:
@@ -417,7 +417,7 @@ class TestBranchTree(unittest.TestCase):
self._write(self.root, "cache-is-a-file", "") self._write(self.root, "cache-is-a-file", "")
with ( with (
patch.dict(os.environ, {"XDG_CACHE_HOME": blocker}), patch.dict(os.environ, {"XDG_CACHE_HOME": blocker}),
patch.object(tree, "secret_service_token", return_value=("t0ken", None)), patch.object(tree, "_forge_access", return_value=("t0ken", None)),
patch.object(tree, "facts_with_token", return_value=ForgeFacts()), patch.object(tree, "facts_with_token", return_value=ForgeFacts()),
): ):
entry = self._entry() entry = self._entry()
+1 -1
View File
@@ -22,7 +22,7 @@ class TestBranchTreeFlow(GcFixture, unittest.TestCase):
patch.object(gc, "host_pid_namespace", return_value=True), patch.object(gc, "host_pid_namespace", return_value=True),
patch.object(gc, "list_compose_containers", return_value=[]), patch.object(gc, "list_compose_containers", return_value=[]),
patch.object(gc, "_process_cwds", return_value={}), patch.object(gc, "_process_cwds", return_value={}),
patch.object(tree, "secret_service_token", return_value=(None, "locked")), patch.object(tree, "_forge_access", return_value=(None, "locked")),
): ):
patcher.start() patcher.start()
self.addCleanup(patcher.stop) self.addCleanup(patcher.stop)
@@ -164,7 +164,7 @@ class TestInstalledVersionDegradation(unittest.TestCase):
self.assertIsNone(get_installed_python_version("kpmx")) self.assertIsNone(get_installed_python_version("kpmx"))
def test_non_json_nix_profile_output_falls_back_to_text_mode(self) -> None: def test_non_json_nix_profile_output_falls_back_to_text_mode(self) -> None:
import pkgmgr.core.version.installed as mod from pkgmgr.core.version import installed as mod
with ( with (
patch.object(mod.shutil, "which", return_value="/usr/bin/nix"), patch.object(mod.shutil, "which", return_value="/usr/bin/nix"),
@@ -173,7 +173,7 @@ class TestInstalledVersionDegradation(unittest.TestCase):
self.assertIsNone(mod.get_installed_nix_profile_version("pkgmgr")) self.assertIsNone(mod.get_installed_nix_profile_version("pkgmgr"))
def test_json_list_instead_of_object_is_tolerated(self) -> None: def test_json_list_instead_of_object_is_tolerated(self) -> None:
import pkgmgr.core.version.installed as mod from pkgmgr.core.version import installed as mod
# Valid JSON, wrong shape: data.get() raises AttributeError on a list. # Valid JSON, wrong shape: data.get() raises AttributeError on a list.
with ( with (
@@ -566,7 +566,7 @@ class TestReleaseFileWriteDegradation(unittest.TestCase):
self.assertIn("Could not read spec file for changelog update", buf.getvalue()) self.assertIn("Could not read spec file for changelog update", buf.getvalue())
def test_unwritable_spec_changelog_is_reported(self) -> None: def test_unwritable_spec_changelog_is_reported(self) -> None:
import pkgmgr.actions.release.files.rpm_changelog as mod from pkgmgr.actions.release.files import rpm_changelog as mod
path = _write( path = _write(
os.path.join(self.dir, "pkg.spec"), os.path.join(self.dir, "pkg.spec"),
+1 -2
View File
@@ -4,7 +4,6 @@ import unittest
from unittest.mock import patch from unittest.mock import patch
import pkgmgr.actions.install as install_module import pkgmgr.actions.install as install_module
from pkgmgr.actions.install import install_repos
from pkgmgr.actions.install.installers.base import BaseInstaller from pkgmgr.actions.install.installers.base import BaseInstaller
@@ -141,7 +140,7 @@ class TestInstallReposIntegration(unittest.TestCase):
old_installers = install_module.INSTALLERS old_installers = install_module.INSTALLERS
install_module.INSTALLERS = [DummyInstaller()] install_module.INSTALLERS = [DummyInstaller()]
try: try:
install_repos( install_module.install_repos(
selected_repos=selected_repos, selected_repos=selected_repos,
repositories_base_dir=tmp_base, repositories_base_dir=tmp_base,
bin_dir=tmp_bin, bin_dir=tmp_bin,
@@ -129,7 +129,7 @@ class TestIntegrationMirrorProbeDetailAndProvision(unittest.TestCase):
] ]
def probe_side_effect(url: str, cwd: str = "."): def probe_side_effect(url: str, cwd: str = "."):
if "github.com" in url: if url == "git@github.com:alice/repo.git":
# show "empty repo reachable" note; setup_cmd prints [OK] and does not print reason for ok # show "empty repo reachable" note; setup_cmd prints [OK] and does not print reason for ok
return ( return (
True, True,
@@ -180,7 +180,7 @@ class TestIntegrationMirrorProbeDetailAndProvision(unittest.TestCase):
] ]
def probe_side_effect(url: str, cwd: str = "."): def probe_side_effect(url: str, cwd: str = "."):
if "github.com" in url: if url == "git@github.com:alice/repo.git":
return True, "" return True, ""
return False, "(exit 128) fatal: Could not read from remote repository." return False, "(exit 128) fatal: Could not read from remote repository."
+2 -4
View File
@@ -6,7 +6,7 @@ import shutil
import subprocess import subprocess
import tempfile import tempfile
import unittest import unittest
from contextlib import redirect_stdout from contextlib import redirect_stdout, suppress
from pathlib import Path from pathlib import Path
from unittest.mock import patch from unittest.mock import patch
@@ -339,10 +339,8 @@ class TestPushMirrorLeases(unittest.TestCase):
hooks_fire = marker.exists() hooks_fire = marker.exists()
marker.unlink(missing_ok=True) marker.unlink(missing_ok=True)
try: with suppress(PushRefusedError):
self._push() self._push()
except PushRefusedError:
pass
self.assertFalse(marker.exists(), f"config hooks fire on commit: {hooks_fire}") self.assertFalse(marker.exists(), f"config hooks fire on commit: {hooks_fire}")
@@ -14,7 +14,6 @@ from collections.abc import Sequence
from unittest.mock import patch from unittest.mock import patch
import pkgmgr.actions.install as install_mod import pkgmgr.actions.install as install_mod
from pkgmgr.actions.install import install_repos
from pkgmgr.actions.install.installers.makefile import MakefileInstaller from pkgmgr.actions.install.installers.makefile import MakefileInstaller
from pkgmgr.actions.install.installers.nix import NixFlakeInstaller from pkgmgr.actions.install.installers.nix import NixFlakeInstaller
from pkgmgr.actions.install.installers.os_packages.arch_pkgbuild import ( from pkgmgr.actions.install.installers.os_packages.arch_pkgbuild import (
@@ -89,7 +88,7 @@ class TestRecursiveCapabilitiesIntegration(unittest.TestCase):
), ),
patch.object(install_mod, "clone_repos"), patch.object(install_mod, "clone_repos"),
): ):
install_repos( install_mod.install_repos(
selected_repos=selected_repos, selected_repos=selected_repos,
repositories_base_dir=self.tmp_root, repositories_base_dir=self.tmp_root,
bin_dir=self.bin_dir, bin_dir=self.bin_dir,
@@ -14,7 +14,7 @@ class TestIntegrationReposCreatePreview(unittest.TestCase):
try: try:
repos_mod = importlib.import_module("pkgmgr.cli.commands.repos") repos_mod = importlib.import_module("pkgmgr.cli.commands.repos")
except ImportError as exc: except ImportError as exc:
self.skipTest(f"CLI module not available: {exc}") raise unittest.SkipTest(f"CLI module not available: {exc}") from exc
handle = getattr(repos_mod, "handle_repos_command", None) handle = getattr(repos_mod, "handle_repos_command", None)
if handle is None: if handle is None:
+1 -1
View File
@@ -58,7 +58,7 @@ class ReviewRepoCase(unittest.TestCase):
def _trap(self, path: str, tail: str) -> str: def _trap(self, path: str, tail: str) -> str:
write(path, f"#!/bin/sh\ntouch '{self.marker}'\n{tail}\n".encode()) write(path, f"#!/bin/sh\ntouch '{self.marker}'\n{tail}\n".encode())
os.chmod(path, 0o755) os.chmod(path, 0o700)
return path return path
def _assert_fires(self, *args: str) -> None: def _assert_fires(self, *args: str) -> None:
+2 -2
View File
@@ -331,7 +331,7 @@ class TestWorktreeUp(WorktreeFixture, unittest.TestCase):
script = os.path.join(self.repo, name) script = os.path.join(self.repo, name)
with open(script, "w") as fh: with open(script, "w") as fh:
fh.write(f"#!/bin/sh\ntouch {marker}\n") fh.write(f"#!/bin/sh\ntouch {marker}\n")
os.chmod(script, 0o755) os.chmod(script, 0o700)
git(self.repo, "add", name) git(self.repo, "add", name)
git(self.repo, "commit", "-m", name) git(self.repo, "commit", "-m", name)
git(self.repo, "push", "origin", "main") git(self.repo, "push", "origin", "main")
@@ -370,7 +370,7 @@ class TestWorktreeUp(WorktreeFixture, unittest.TestCase):
fake = os.path.join(planted, "true") fake = os.path.join(planted, "true")
with open(fake, "w") as fh: with open(fake, "w") as fh:
fh.write(f"#!/bin/sh\ntouch {marker}\n") fh.write(f"#!/bin/sh\ntouch {marker}\n")
os.chmod(fake, 0o755) os.chmod(fake, 0o700)
if os.getuid() == 0: if os.getuid() == 0:
os.chown(planted, 65534, 65534) os.chown(planted, 65534, 65534)
os.chown(fake, 65534, 65534) os.chown(fake, 65534, 65534)
@@ -31,7 +31,7 @@ def item(locked: bool, secret: bytes = b"t0ken") -> MagicMock:
class TestSecretServiceToken(unittest.TestCase): class TestSecretServiceToken(unittest.TestCase):
def _token(self, module: types.ModuleType) -> tuple[str | None, str | None]: def _token(self, module: types.ModuleType) -> tuple[str | None, str | None]:
with patch.dict(sys.modules, {"secretstorage": module}): with patch.dict(sys.modules, {"secretstorage": module}):
return tree.secret_service_token() return tree._forge_access()
def test_a_locked_item_is_never_unlocked(self) -> None: def test_a_locked_item_is_never_unlocked(self) -> None:
locked = item(True) locked = item(True)
@@ -4,9 +4,8 @@ import json
import os import os
import shutil import shutil
import tempfile import tempfile
import unittest import unittest.mock
from types import SimpleNamespace from types import SimpleNamespace
from unittest import mock
from pkgmgr.actions.code_scanning import ( from pkgmgr.actions.code_scanning import (
CodeScanningError, CodeScanningError,
@@ -52,11 +51,13 @@ class TestDownloadCodeScanning(unittest.TestCase):
def test_writes_alerts_summary_and_analyses(self) -> None: def test_writes_alerts_summary_and_analyses(self) -> None:
with tempfile.TemporaryDirectory() as tmp: with tempfile.TemporaryDirectory() as tmp:
with ( with (
mock.patch( unittest.mock.patch(
"pkgmgr.actions.code_scanning.shutil.which", "pkgmgr.actions.code_scanning.shutil.which",
return_value="/usr/bin/gh", return_value="/usr/bin/gh",
), ),
mock.patch("pkgmgr.actions.code_scanning._gh", side_effect=_fake_gh), unittest.mock.patch(
"pkgmgr.actions.code_scanning._gh", side_effect=_fake_gh
),
): ):
result = download_code_scanning(output_dir=tmp) result = download_code_scanning(output_dir=tmp)
@@ -74,10 +75,12 @@ class TestDownloadCodeScanning(unittest.TestCase):
def test_default_output_dir_uses_repo_name(self) -> None: def test_default_output_dir_uses_repo_name(self) -> None:
with ( with (
mock.patch( unittest.mock.patch(
"pkgmgr.actions.code_scanning.shutil.which", return_value="/usr/bin/gh" "pkgmgr.actions.code_scanning.shutil.which", return_value="/usr/bin/gh"
), ),
mock.patch("pkgmgr.actions.code_scanning._gh", side_effect=_fake_gh), unittest.mock.patch(
"pkgmgr.actions.code_scanning._gh", side_effect=_fake_gh
),
): ):
result = download_code_scanning() result = download_code_scanning()
self.addCleanup(shutil.rmtree, "/tmp/pkgmgr-cs-test", ignore_errors=True) self.addCleanup(shutil.rmtree, "/tmp/pkgmgr-cs-test", ignore_errors=True)
@@ -88,7 +91,9 @@ class TestDownloadCodeScanning(unittest.TestCase):
def test_errors_when_gh_missing(self) -> None: def test_errors_when_gh_missing(self) -> None:
with ( with (
mock.patch("pkgmgr.actions.code_scanning.shutil.which", return_value=None), unittest.mock.patch(
"pkgmgr.actions.code_scanning.shutil.which", return_value=None
),
self.assertRaises(CodeScanningError), self.assertRaises(CodeScanningError),
): ):
download_code_scanning(output_dir="/tmp/should-not-be-created") download_code_scanning(output_dir="/tmp/should-not-be-created")
@@ -26,11 +26,6 @@ class TestMakefileInstaller(unittest.TestCase):
) )
self.installer = MakefileInstaller() self.installer = MakefileInstaller()
# @patch("os.path.exists", return_value=True)
# def test_supports_true_when_makefile_exists(self, mock_exists):
# self.assertTrue(self.installer.supports(self.ctx))
# mock_exists.assert_called_with(os.path.join(self.ctx.repo_dir, "Makefile"))
@patch("os.path.exists", return_value=False) @patch("os.path.exists", return_value=False)
def test_supports_false_when_makefile_missing(self, mock_exists): def test_supports_false_when_makefile_missing(self, mock_exists):
self.assertFalse(self.installer.supports(self.ctx)) self.assertFalse(self.installer.supports(self.ctx))
@@ -1,7 +1,6 @@
from __future__ import annotations from __future__ import annotations
import unittest import unittest.mock
from unittest import mock
from pkgmgr.actions.release.files.editor import _open_editor_for_changelog from pkgmgr.actions.release.files.editor import _open_editor_for_changelog
@@ -16,7 +15,7 @@ class TestOpenEditorForChangelog(unittest.TestCase):
seen["text"] = handle.read() seen["text"] = handle.read()
return 0 return 0
with mock.patch( with unittest.mock.patch(
"pkgmgr.actions.release.files.editor.subprocess.call", side_effect=record "pkgmgr.actions.release.files.editor.subprocess.call", side_effect=record
): ):
_open_editor_for_changelog(**kwargs) _open_editor_for_changelog(**kwargs)
@@ -44,7 +43,7 @@ class TestOpenEditorForChangelog(unittest.TestCase):
seen["text"] = handle.read() seen["text"] = handle.read()
return 0 return 0
with mock.patch( with unittest.mock.patch(
"pkgmgr.actions.release.files.editor.subprocess.call", side_effect=rewrite "pkgmgr.actions.release.files.editor.subprocess.call", side_effect=rewrite
): ):
kept = _open_editor_for_changelog( kept = _open_editor_for_changelog(
+6 -7
View File
@@ -19,10 +19,9 @@ import os
import sys import sys
import tempfile import tempfile
import textwrap import textwrap
import unittest import unittest.mock
from contextlib import redirect_stdout from contextlib import redirect_stdout
from typing import Any from typing import Any
from unittest import mock
from pkgmgr import cli from pkgmgr import cli
@@ -71,7 +70,7 @@ class TestCliVersion(unittest.TestCase):
} }
# Patch load_config so cli.main() does not read real config files # Patch load_config so cli.main() does not read real config files
self._patch_load_config = mock.patch( self._patch_load_config = unittest.mock.patch(
"pkgmgr.cli.load_config", return_value=_fake_config() "pkgmgr.cli.load_config", return_value=_fake_config()
) )
self.mock_load_config = self._patch_load_config.start() self.mock_load_config = self._patch_load_config.start()
@@ -79,7 +78,7 @@ class TestCliVersion(unittest.TestCase):
# Patch the "current directory" selection used by dispatch_command(). # Patch the "current directory" selection used by dispatch_command().
# This matches the new behaviour: without explicit identifiers, # This matches the new behaviour: without explicit identifiers,
# version uses _select_repo_for_current_directory(ctx). # version uses _select_repo_for_current_directory(ctx).
self._patch_select_repo_for_current_directory = mock.patch( self._patch_select_repo_for_current_directory = unittest.mock.patch(
"pkgmgr.cli.dispatch._select_repo_for_current_directory", "pkgmgr.cli.dispatch._select_repo_for_current_directory",
return_value=[self._fake_repo], return_value=[self._fake_repo],
) )
@@ -165,7 +164,7 @@ class TestCliVersion(unittest.TestCase):
self._write_pyproject("1.2.3") self._write_pyproject("1.2.3")
# Arrange: mock git tags used by handle_version # Arrange: mock git tags used by handle_version
with mock.patch( with unittest.mock.patch(
"pkgmgr.cli.commands.version.get_tags", "pkgmgr.cli.commands.version.get_tags",
return_value=["v1.2.0", "v1.2.3", "v1.0.0"], return_value=["v1.2.0", "v1.2.3", "v1.0.0"],
): ):
@@ -197,7 +196,7 @@ class TestCliVersion(unittest.TestCase):
self._write_pyproject("1.2.4") self._write_pyproject("1.2.4")
# Arrange: mock git tags (latest is 1.2.3) # Arrange: mock git tags (latest is 1.2.3)
with mock.patch( with unittest.mock.patch(
"pkgmgr.cli.commands.version.get_tags", "pkgmgr.cli.commands.version.get_tags",
return_value=["v1.2.3"], return_value=["v1.2.3"],
): ):
@@ -225,7 +224,7 @@ class TestCliVersion(unittest.TestCase):
self._write_pyproject("0.0.1") self._write_pyproject("0.0.1")
# Arrange: no tags returned # Arrange: no tags returned
with mock.patch( with unittest.mock.patch(
"pkgmgr.cli.commands.version.get_tags", "pkgmgr.cli.commands.version.get_tags",
return_value=[], return_value=[],
): ):
+1 -1
View File
@@ -79,7 +79,7 @@ class TestCreateInk(unittest.TestCase):
command_path = os.path.join(repo_dir, "main.sh") command_path = os.path.join(repo_dir, "main.sh")
with open(command_path, "w", encoding="utf-8") as f: with open(command_path, "w", encoding="utf-8") as f:
f.write("#!/bin/sh\necho mytool\n") f.write("#!/bin/sh\necho mytool\n")
os.chmod(command_path, 0o755) os.chmod(command_path, 0o700)
repo = { repo = {
"command": command_path, "command": command_path,
+1 -1
View File
@@ -149,7 +149,7 @@ class TestGitRun(unittest.TestCase):
self.assertEqual(self._kept(env), ["GIT_CEILING_DIRECTORIES"]) self.assertEqual(self._kept(env), ["GIT_CEILING_DIRECTORIES"])
self.assertIsNone(env.get("GIT_CONFIG_NOSYSTEM")) self.assertIsNone(env.get("GIT_CONFIG_NOSYSTEM"))
self.assertEqual(env.get("HOME"), home) self.assertEqual(env.get("HOME"), home)
self.assertFalse("XDG_CONFIG_HOME" in env) self.assertNotIn("XDG_CONFIG_HOME", env)
def test_failure_raises_giterror_with_details(self) -> None: def test_failure_raises_giterror_with_details(self) -> None:
# Build a CalledProcessError with stdout/stderr populated # Build a CalledProcessError with stdout/stderr populated