Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions .devcontainer/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
# "Instance extension points".

# renovate: datasource=github-releases depName=j178/prek
ARG PREK_VERSION=0.5.9
ARG PREK_VERSION=0.5.10

# renovate: datasource=npm depName=@anthropic-ai/claude-code
ARG CLAUDE_CODE_VERSION=2.1.316
ARG CLAUDE_CODE_VERSION=2.1.319

# renovate: datasource=github-releases depName=edouard-claude/snip
ARG SNIP_VERSION=0.25.2
ARG SNIP_VERSION=0.26.0

# renovate: datasource=github-releases depName=cli/cli
ARG GH_VERSION=2.103.3
Expand All @@ -22,7 +22,7 @@ ARG GH_VERSION=2.103.3
# package. Left on PATH afterward; harmless, and an instance that adds
# Python as its own application runtime can reuse it directly.
# renovate: datasource=github-releases depName=astral-sh/uv
ARG UV_VERSION=0.13.6
ARG UV_VERSION=0.13.7

# python3 is infrastructure tooling, not an application runtime this
# template assumes: prek needs an interpreter to build the venv for any
Expand Down
6 changes: 4 additions & 2 deletions .github/CONTENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@
language's own package manifest (e.g. `pyproject.toml`, `Cargo.toml`,
`package.json`). All patch/minor updates are grouped into a single
weekly PR that automerges once required checks pass; all major updates
are grouped into a separate PR for manual review. A Python minor
upgrade (e.g. 3.14 to 3.15) also gets its own PR for manual review:
are grouped into a separate PR for manual review. Python 3.15 is held
(`allowedVersions: "<3.15"`) until uv, pip-audit and pydantic-core
support it; see `../docs/TEMPLATE.md`. A Python minor
upgrade (e.g. 3.14 to 3.16) also gets its own PR for manual review:
it passes this repo's checks, but for an instance running Python as
its app runtime it's a runtime upgrade (its runtime `Dockerfile` must
match, and its tools must support the new version). Devcontainer
Expand Down
5 changes: 5 additions & 0 deletions .github/renovate.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@
"groupName": "python minor upgrade",
"automerge": false
},
{
"description": "HOLD: no Python 3.15 yet (allowedVersions <3.15, any datasource or manager that names the dependency python: the python-version datasource, the python Docker image, .python-version, requires-python). Bumps to 3.15.2 failed across the template family: uv has no cpython-3.15.2 download, pip-audit crashes on the removed sre_constants, and pydantic-core has no cp315 wheel on arm64. Lift this rule once uv offers 3.15 builds and pip-audit and pydantic-core support 3.15.",
"matchDepNames": ["python"],
"allowedVersions": "<3.15"
},
{
"description": "Pin container images to their digest. Scoped to the docker managers on purpose: a global pinDigests also hits the pre-commit manager, whose tag revs can't be converted to digests (the update fails). GitHub Actions are pinned by helpers:pinGitHubActionDigests instead.",
"matchManagers": ["dockerfile", "docker-compose"],
Expand Down
5 changes: 5 additions & 0 deletions .github/scripts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@
disk. CI is safe because the runner checkout is discarded and the sync
state does not advance. After a failed manual run, reset the working tree
with `git checkout -- .` and then `git clean -fd` (separate commands).
- `git_test_env.py` — `git_env()`, the environment every test that runs real
`git` must use: it drops all inherited `GIT_*` variables (a git hook exports
`GIT_DIR`, `GIT_INDEX_FILE`, ... which would make a scratch repo's `git add`
or `git init --bare` act on the outer repository, e.g. flipping its
`core.bare`) and keeps only a test identity.
- `test_template_sync.py` — stdlib `unittest` tests for
`template_sync.py`'s replace and merge tiers (including the executable
bit, re-running a merge, symlinked destinations, and `git merge-file`
Expand Down
36 changes: 36 additions & 0 deletions .github/scripts/git_test_env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
"""Scrubbed environment for tests that run real ``git``.

Run as a git hook (``prek`` under ``git commit``), the tests inherit
``GIT_DIR``, ``GIT_INDEX_FILE``, ``GIT_WORK_TREE`` and friends from the outer
repository, so a scratch repo's ``git add`` or ``git init`` would act on the
outer one instead (a stray file in its index, ``git init --bare`` turning it
bare). Every test that spawns real git builds its environment with
``git_env`` so that cannot happen.
"""

from __future__ import annotations

import os
from collections.abc import Mapping

# Test identity: the only GIT_* variables a scratch repo needs.
IDENTITY = {
"GIT_AUTHOR_NAME": "t",
"GIT_AUTHOR_EMAIL": "t@example.com",
"GIT_COMMITTER_NAME": "t",
"GIT_COMMITTER_EMAIL": "t@example.com",
}


def git_env(base: Mapping[str, str] | None = None) -> dict[str, str]:
"""Return ``base`` (default ``os.environ``) without any ``GIT_*``, plus a test identity.

The system and global git config are disabled too, so a developer's
``core.*`` or hooks settings cannot leak in.
"""
source = os.environ if base is None else base
env = {k: v for k, v in source.items() if not k.startswith("GIT_")}
env.update(IDENTITY)
env["GIT_CONFIG_NOSYSTEM"] = "1"
env["GIT_CONFIG_GLOBAL"] = os.devnull
return env
6 changes: 6 additions & 0 deletions .github/scripts/moderate_package_result.sh
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@ case "$mode" in build | triage) ;; *)
esac
[[ "${GITHUB_ISSUE_NUMBER:-}" =~ ^[0-9]+$ ]] || { echo "::error::GITHUB_ISSUE_NUMBER is not numeric" >&2; exit 1; }

# A repository-location variable inherited from the caller (a git hook exports
# them) would make the `git init --bare` below re-initialise the caller's own
# repository instead of the scratch one. Commit identity variables are kept.
unset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE GIT_OBJECT_DIRECTORY \
GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_COMMON_DIR GIT_NAMESPACE GIT_PREFIX

mkdir -p "$out_dir"
safe="$(mktemp -d)"
trap 'rm -rf "$safe"' EXIT
Expand Down
19 changes: 17 additions & 2 deletions .github/scripts/template_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,11 @@ def relative_files_matching(
return [rel for rel in listing if matches(rel, pattern)]


def is_bytecode(rel: str) -> bool:
"""Whether ``rel`` is Python bytecode (``__pycache__/`` or ``*.pyc``), never synced."""
return rel.endswith(".pyc") or "__pycache__" in rel.split("/")


def tier_paths(root: Path, tiers: dict[str, list[str]], tier: str) -> set[str]:
"""Return every file under ``root`` classified into ``tier`` by the manifest."""
candidates: set[str] = set()
Expand All @@ -205,7 +210,9 @@ def tier_paths(root: Path, tiers: dict[str, list[str]], tier: str) -> set[str]:
continue
rel = pattern.rstrip("/") if pattern.endswith("/") else pattern
candidates.update(relative_files_under(root, rel))
return {path for path in candidates if classify(path, tiers) == [tier]}
return {
path for path in candidates if not is_bytecode(path) and classify(path, tiers) == [tier]
}


def is_executable(path: Path) -> bool:
Expand Down Expand Up @@ -443,7 +450,15 @@ def cmd_check_apply(args: argparse.Namespace) -> int:

def pr_body(summary: dict[str, dict[str, list[str]]], old_tag: str, new_tag: str, repo: str) -> str:
"""Render the sync PR body markdown from an ``apply`` summary."""
lines = [f"Syncs from `{old_tag}` to `{new_tag}` of {repo}.", "", "### Files changed"]
lines = [f"Syncs from `{old_tag}` to `{new_tag}` of {repo}."]
if summary["merge"]["conflicts"]:
lines += [
"",
"> [!WARNING]",
"> **Needs manual resolution.** This PR is a draft because the merge left "
"conflicts (listed below). Resolve them, then mark it ready for review.",
]
lines += ["", "### Files changed"]
for path in summary["replace"]["updated"]:
lines.append(f"- replace: `{path}`")
for path in summary["replace"]["removed"]:
Expand Down
62 changes: 54 additions & 8 deletions .github/scripts/test_moderate_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,30 +10,76 @@
import unittest
from pathlib import Path

from git_test_env import git_env

SCRIPTS = Path(__file__).resolve().parent
GIT_ENV = {
"GIT_AUTHOR_NAME": "t",
"GIT_AUTHOR_EMAIL": "t@example.com",
"GIT_COMMITTER_NAME": "t",
"GIT_COMMITTER_EMAIL": "t@example.com",
}


def run(
argv: list[str], cwd: Path | None = None, env: dict[str, str] | None = None, stdin: bytes = b""
) -> subprocess.CompletedProcess[bytes]:
"""Run a fixed argv with a merged environment."""
"""Run a fixed argv with a scrubbed (no inherited ``GIT_*``) merged environment."""
return subprocess.run( # noqa: S603 -- fixed argv, trusted scripts
argv,
cwd=cwd,
env={**os.environ, **GIT_ENV, **(env or {})},
env={**git_env(), **(env or {})},
input=stdin,
capture_output=True,
check=False,
timeout=60,
)


class GitEnvIsolationTest(unittest.TestCase):
"""The helpers must not let an outer repo's ``GIT_*`` reach a scratch repo."""

@unittest.skipUnless(shutil.which("git"), "git is required")
def test_decoy_repo_is_untouched(self) -> None:
"""With GIT_DIR/GIT_INDEX_FILE pointing at a decoy, git acts on the scratch repo only."""
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
decoy, scratch = root / "decoy", root / "scratch"
decoy.mkdir()
scratch.mkdir()
plain = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
subprocess.run( # noqa: S603 -- fixed argv
["git", "init", "-q", str(decoy)], # noqa: S607
check=True,
env=plain,
)
config_before = (decoy / ".git/config").read_bytes()
leaked = {
**os.environ,
"GIT_DIR": str(decoy / ".git"),
"GIT_INDEX_FILE": str(decoy / ".git/index"),
"GIT_WORK_TREE": str(decoy),
}
for argv in (["init", "-q", "-b", "main"], ["config", "core.bare", "true"]):
proc = subprocess.run( # noqa: S603 -- fixed argv
["git", *argv], # noqa: S607
cwd=scratch,
env=git_env(leaked),
capture_output=True,
check=False,
)
self.assertEqual(proc.returncode, 0, proc.stderr)
(scratch / "a.txt").write_text("x\n")
run(["git", "add", "a.txt"], cwd=scratch) # run() scrubs the real environment too
self.assertTrue((scratch / ".git").is_dir())
self.assertEqual((decoy / ".git/config").read_bytes(), config_before)
self.assertFalse((decoy / ".git/index").exists())
self.assertFalse((decoy / "a.txt").exists())

def test_git_env_drops_everything_but_the_identity(self) -> None:
"""Only the test identity and the config isolation survive."""
env = git_env({"GIT_DIR": "x", "GIT_CONFIG": "y", "PATH": "/bin"})
self.assertEqual(env["PATH"], "/bin")
self.assertNotIn("GIT_DIR", env)
self.assertNotIn("GIT_CONFIG", env)
self.assertEqual(env["GIT_AUTHOR_NAME"], "t")
self.assertEqual(env["GIT_CONFIG_NOSYSTEM"], "1")


class CheckPathsTest(unittest.TestCase):
"""``moderate_check_paths.sh`` denies what runs with credentials and allows the rest."""

Expand Down
75 changes: 75 additions & 0 deletions .github/scripts/test_template_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -862,6 +862,81 @@ def directly_invoked_scripts(workflow_text: str) -> set[str]:
return invoked


class BytecodeExcludedTest(unittest.TestCase):
"""Python bytecode never syncs: running the script in a checkout creates it."""

def test_tier_paths_skips_pycache_and_pyc(self) -> None:
"""A replace directory and a glob both skip ``__pycache__/`` and ``*.pyc``."""
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
for rel in (
".github/scripts/a.py",
".github/scripts/__pycache__/a.cpython-314.pyc",
".github/scripts/sub/__pycache__/b.txt",
".github/scripts/stray.pyc",
"cfg/x.json",
"cfg/__pycache__/x.json",
):
write(root / rel, b"x\n", 0o644)
tiers: dict[str, list[str]] = {
"replace": [".github/scripts/", "cfg/*"],
"ignore": [],
"merge": [],
}
self.assertEqual(
template_sync.tier_paths(root, tiers, "replace"),
{".github/scripts/a.py", "cfg/x.json"},
)

def test_apply_does_not_copy_bytecode_into_the_instance(self) -> None:
"""End to end: a stray ``__pycache__`` in the new template stays out."""
with tempfile.TemporaryDirectory() as tmp:
old, new, inst = (Path(tmp) / n for n in ("old", "new", "inst"))
for d in (old, new, inst):
d.mkdir()
write(new / "s/a.py", b"print(1)\n", 0o644)
write(new / "s/__pycache__/a.pyc", b"\0\1", 0o644)
paths = template_sync.tier_paths(
new, {"replace": ["s/"], "ignore": [], "merge": []}, "replace"
)
template_sync.apply_replace(old, new, inst, paths)
self.assertTrue((inst / "s/a.py").exists())
self.assertFalse((inst / "s/__pycache__").exists())


class ConflictedSyncIsDraftTest(unittest.TestCase):
"""A sync whose merge left conflicts must open as a draft naming the files."""

CONFLICT = {
"replace": {"updated": [], "removed": []},
"merge": {"merged": [], "conflicts": [".github/renovate.json"], "binary": []},
}
CLEAN = {
"replace": {"updated": [], "removed": []},
"merge": {"merged": ["README.md"], "conflicts": [], "binary": []},
}

def test_body_flags_manual_resolution_and_lists_files(self) -> None:
"""The body leads with a warning and lists each conflicted file."""
body = template_sync.pr_body(self.CONFLICT, "v1.0.0", "v1.1.0", "o/t")
self.assertIn("Needs manual resolution", body)
self.assertIn("draft", body)
self.assertIn("`.github/renovate.json`", body)

def test_clean_body_has_no_warning(self) -> None:
"""A clean sync's body is unchanged."""
body = template_sync.pr_body(self.CLEAN, "v1.0.0", "v1.1.0", "o/t")
self.assertNotIn("Needs manual resolution", body)

def test_workflow_opens_conflicted_sync_as_draft(self) -> None:
"""The workflow passes ``--draft`` on ``conflicts=1`` and disables bytecode."""
text = (REPO_ROOT / ".github/workflows/template-sync.yml").read_text()
self.assertIn("CONFLICTS: ${{ steps.apply.outputs.conflicts }}", text)
self.assertIn('if [ "$CONFLICTS" = "1" ]; then\n draft=(--draft)', text)
self.assertIn('gh pr create "${draft[@]}"', text)
self.assertIn('PYTHONDONTWRITEBYTECODE: "1"', text)


class DirectlyInvokedScriptsAreExecutableTest(unittest.TestCase):
"""A workflow step that names a script as the command needs mode 755 (exit 126 otherwise)."""

Expand Down
2 changes: 1 addition & 1 deletion .github/template-sync-state.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"template_repo": "craftainer/template-base",
"synced_tag": "v1.15.1"
"synced_tag": "v1.15.3"
}
14 changes: 11 additions & 3 deletions .github/workflows/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
[`devcontainers/ci`](https://github.com/devcontainers/ci)), under a
per-run `COMPOSE_PROJECT_NAME` that a final step tears down. Runs as a
two-leg `amd64`/`arm64` matrix (see "Architecture matrix" below).
A step before the hooks runs `../scripts/semver_release_type.py` when an
instance or downstream template ships it (template-rust-crate does; base
does not, so the step is skipped here) and the hooks step forwards its
`SEMVER_RELEASE_TYPE` into the container, so a `!`-marked PR title (or, on
`main`, head commit subject) runs `cargo semver-checks` as `major`.
- `smoke.yml` — builds the `runner` stage of the root `Dockerfile` via
the root `compose.yml`, starts it against the real Postgres, RustFS,
Redis, and Keycloak backing services, and confirms `/health/live` and
Expand Down Expand Up @@ -51,8 +56,8 @@
schedule or `workflow_dispatch`, diffs the instance against the
template's latest tagged release per the manifest's tiers and opens a
PR — never a direct push, never auto-merged.
`template_sync.py apply` exits 0 (clean), 1 (merge conflicts, still
opens the PR) or 2 (error, e.g. an unreadable manifest or `git
`template_sync.py apply` exits 0 (clean), 1 (merge conflicts: the PR is still
opened, as a draft whose body says it needs manual resolution) or 2 (error, e.g. an unreadable manifest or `git
merge-file` failing): every failure other than conflicts exits 2. A
binary merge-tier file the instance changed cannot be merged, so it is
reported as a conflict and the instance's copy is left as it is. A crash before
Expand All @@ -62,7 +67,10 @@
fails the job before the sync state advances. The job then exits with
`apply`'s own status when that is 2 or higher (so the log and the step's
exit code tell an error from conflicts) and the summary is printed as valid
only after that check.
only after that check. The sync never copies Python bytecode
(`__pycache__/`, `*.pyc`), and the apply step sets
`PYTHONDONTWRITEBYTECODE` so running the script cannot create any in the
template checkout.

Every workflow's `runs-on` defaults to `ubuntu-24.04` but can be
overridden with the `CI_RUNNER` repository/organization variable —
Expand Down
20 changes: 20 additions & 0 deletions .github/workflows/checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,22 @@ jobs:
cache-from: type=gha,scope=${{ matrix.arch }}
cache-to: type=gha,mode=max,scope=${{ matrix.arch }}

# Optional instance script: a template that ships
# .github/scripts/semver_release_type.py (template-rust-crate) gets
# SEMVER_RELEASE_TYPE=major for a `!`-marked PR title (or, on main, head
# commit subject), which the hooks step forwards into the container.
# Base ships no such script, so the step is skipped here. The title and
# message are attacker-controlled and so reach the script only as
# environment variables, never interpolated into `run:`.
- name: Pick the semver-checks release type
if: hashFiles('.github/scripts/semver_release_type.py') != ''
env:
EVENT_NAME: ${{ github.event_name }}
REF: ${{ github.ref }}
PR_TITLE: ${{ github.event.pull_request.title }}
COMMIT_MESSAGE: ${{ github.event.head_commit.message }}
run: python3 -I .github/scripts/semver_release_type.py >> "$GITHUB_ENV"

# --hook-stage manual runs every hook (both the fast pre-commit-stage
# ones and the extensive pre-push-stage ones) in one pass, inside the
# devcontainer -- the same environment (uv, prek, playwright, ...) a
Expand All @@ -75,8 +91,12 @@ jobs:
GH_TOKEN: ${{ github.token }}
with:
runCmd: prek run --all-files --hook-stage manual
# SEMVER_RELEASE_TYPE comes from the step above; devcontainers/ci
# omits a name that is unset or empty, so the hooks' own default
# applies (and base, which has no such step, is unaffected).
env: |
GH_TOKEN
SEMVER_RELEASE_TYPE

# devcontainers/ci starts the full compose stack (see
# .devcontainer/devcontainer.json's dockerComposeFile) but never
Expand Down
Loading
Loading