From fd8ab72640c6343a4a62f78346e0d35d21939379 Mon Sep 17 00:00:00 2001 From: Michael Johnson Date: Tue, 24 Nov 2026 07:07:44 -0500 Subject: [PATCH] fix: retire woodpecker and ci-prepare, harden init and asset downloads Remove legacy Woodpecker CI backend, templates, bootstrap.sh, dbuild-ci.sh, and ci-prepare, and switch init --category default from Apps to None with VALID_CATEGORIES validation. Guard init --freebsd-port against path traversal and glob patterns, validate image names, escape double-quoted YAML strings in compose.yaml, restrict fetch downloads to http/https with timeout and size bounds, fail on unrecognized screenshot MIME types, remove unused DockerHub description code, and isolate release.yaml publish permissions. --- .github/workflows/ci.yaml | 5 + .github/workflows/release.yaml | 36 +++++-- README.md | 14 +-- bootstrap.sh | 31 ------ dbuild-ci.sh | 47 --------- dbuild/ci/__init__.py | 4 - dbuild/ci/woodpecker.py | 113 -------------------- dbuild/ci_run.py | 14 +-- dbuild/cli.py | 37 +------ dbuild/detect.py | 6 +- dbuild/fetch.py | 45 +++++++- dbuild/init.py | 55 ++++++++-- dbuild/prepare.py | 151 --------------------------- dbuild/registry/dockerhub.py | 68 +----------- dbuild/templates/woodpecker.yaml | 34 ------ dbuild/upstream_assets.py | 11 +- docs/dbuild.1 | 30 +----- tests/test_ci.py | 38 +------ tests/test_ci_run.py | 38 +------ tests/test_cli.py | 35 +++---- tests/test_fetch.py | 160 +++++++++++++++++++++++++++- tests/test_init.py | 103 +++++++++++++++++- tests/test_prepare.py | 174 ------------------------------- tests/test_registry.py | 5 + 24 files changed, 433 insertions(+), 821 deletions(-) delete mode 100755 bootstrap.sh delete mode 100755 dbuild-ci.sh delete mode 100644 dbuild/ci/woodpecker.py delete mode 100644 dbuild/prepare.py delete mode 100644 dbuild/templates/woodpecker.yaml delete mode 100644 tests/test_prepare.py diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 2841dbc..3ef3564 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -5,6 +5,9 @@ on: push: branches: [main] +permissions: + contents: read + jobs: test: runs-on: ubuntu-latest @@ -14,6 +17,8 @@ jobs: python-version: ['3.11', '3.13'] steps: - uses: actions/checkout@v7 + with: + persist-credentials: false - uses: actions/setup-python@v7 with: diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 24d8e61..b6417f5 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -15,16 +15,30 @@ permissions: contents: read jobs: - release: + test: runs-on: ubuntu-latest permissions: - contents: write + contents: read env: - TAG: ${{ github.event.inputs.tag || github.ref_name }} + TAG: ${{ inputs.tag || github.ref_name }} steps: + - name: Validate tag format + run: | + case "$TAG" in + ""|*[!A-Za-z0-9._-]*|-*|*..*) + echo "::error::Invalid release tag: $TAG" + exit 1 + ;; + esac + if ! printf '%s\n' "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.]+)?$'; then + echo "::error::Tag must match vX.Y.Z[-suffix]: $TAG" + exit 1 + fi + - uses: actions/checkout@v7 with: - ref: ${{ github.event.inputs.tag || github.ref }} + ref: ${{ inputs.tag || github.ref }} + persist-credentials: false # Image CI pins the dbuild release in daemonless/workflows (DBUILD_REF), # bumped there by PR after this release. @@ -44,6 +58,14 @@ jobs: pip install -e '.[dev,screenshot]' python -m pytest tests/ -q + publish: + needs: test + runs-on: ubuntu-latest + permissions: + contents: write + env: + TAG: ${{ inputs.tag || github.ref_name }} + steps: # Create once; a re-run on a tag that already has one does nothing. - name: Publish release env: @@ -55,10 +77,10 @@ jobs: exit 0 fi # A hyphen (v1.11.0-rc1) is a pre-release, never marked Latest. - PRE="" - case "${VERSION}" in *-*) PRE="--prerelease" ;; esac + set -- + case "${VERSION}" in *-*) set -- --prerelease ;; esac gh release create "${TAG}" \ --repo "${{ github.repository }}" \ --title "v${VERSION}" \ --generate-notes \ - $PRE + "$@" diff --git a/README.md b/README.md index 802ec39..205b802 100644 --- a/README.md +++ b/README.md @@ -4,10 +4,10 @@ Build, test, and push FreeBSD OCI container images. dbuild is a build tool for [daemonless](https://github.com/daemonless) container images. It reads a project directory containing `Containerfile` templates and an optional `.daemonless/config.yaml`, then handles the full image lifecycle: build, integration test, SBOM generation, and registry push. -It runs the same way locally and in CI. GitHub Actions and Woodpecker call dbuild — dbuild handles the FreeBSD-specific logic (variant detection, architecture mapping, OCI labels, registry auth, skip directives, SBOM generation) so CI workflows stay generic. +It runs the same way locally and in CI. GitHub Actions calls dbuild — dbuild handles the FreeBSD-specific logic (variant detection, architecture mapping, OCI labels, registry auth, skip directives, SBOM generation) so CI workflows stay generic. ``` -GitHub Actions / Woodpecker / local +GitHub Actions / local └── dbuild detect → build matrix └── dbuild build → podman build per variant └── dbuild test → container integration tests @@ -251,7 +251,6 @@ Output the build matrix as JSON for CI integration. ```sh dbuild detect # plain JSON to stdout dbuild detect --format github # write to $GITHUB_OUTPUT -dbuild detect --format woodpecker # JSON to stdout ``` ### `dbuild info` @@ -279,7 +278,6 @@ Scaffold a new dbuild project with starter files. ```sh dbuild init # config.yaml, compose.yaml, Containerfile.j2, root/ dbuild init --github # + GitHub Actions workflow -dbuild init --woodpecker # + Woodpecker CI pipeline ``` The image is a single process on `base-exec`: `/init` runs the setup script @@ -365,14 +363,6 @@ This generates `.github/workflows/build.yaml` which: 2. Spins up a FreeBSD VM per matrix entry (via vmactions/freebsd-vm) 3. Runs `dbuild build → test → sbom → push` inside the VM -### Woodpecker CI - -```sh -dbuild init --woodpecker -``` - -Generates `.woodpecker.yaml`. The pipeline fetches `dbuild-ci.sh` which runs the full build pipeline on the native FreeBSD agent. - ### Local development ```sh diff --git a/bootstrap.sh b/bootstrap.sh deleted file mode 100755 index 87cc243..0000000 --- a/bootstrap.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh -# bootstrap.sh — Prepare a FreeBSD CI environment for dbuild. -# -# Installs python3, fetches dbuild, and runs ci-prepare (which installs -# podman, buildah, skopeo, trivy, ocijail, and configures networking). -# -# Default: fetched from GitHub by the CI workflow template. -# Override: place .daemonless/bootstrap.sh in your image repo. -# -# Environment: -# DBUILD_REF - dbuild version to fetch (default: v1.9.0) -# DBUILD_DIR - install location (default: /tmp/dbuild) - -set -e - -DBUILD_REF="${DBUILD_REF:-v1.9.0}" -DBUILD_DIR="${DBUILD_DIR:-/tmp/dbuild}" - -# ── Install python3 + PyYAML (minimum to run dbuild) ──────────────── -mkdir -p /etc/pkg -echo 'FreeBSD: { url: "http://pkg.FreeBSD.org/${ABI}/latest" }' > /etc/pkg/FreeBSD.conf -pkg update -f && pkg install -y python3 py311-yaml - -# ── Fetch dbuild ──────────────────────────────────────────────────── -fetch -qo /tmp/dbuild.tar.gz \ - "https://github.com/daemonless/dbuild/archive/${DBUILD_REF}.tar.gz" -mkdir -p "$DBUILD_DIR" -tar -xzf /tmp/dbuild.tar.gz -C "$DBUILD_DIR" --strip-components=1 - -# ── Prepare build environment ─────────────────────────────────────── -PYTHONPATH="$DBUILD_DIR" python3 -m dbuild ci-prepare diff --git a/dbuild-ci.sh b/dbuild-ci.sh deleted file mode 100755 index 8eb8c74..0000000 --- a/dbuild-ci.sh +++ /dev/null @@ -1,47 +0,0 @@ -#!/bin/sh -# -# dbuild CI wrapper (backward-compatibility shim) -# -# This script now delegates to `dbuild ci-run`. It is kept for -# repos that still reference dbuild-ci.sh directly. -# -# Usage: sh dbuild-ci.sh [VARIANT] -# -# Env vars: -# DBUILD_REF - override the dbuild version to fetch (default: main) -# DBUILD_PATH - explicit path to dbuild checkout (skips fetch) -# GITHUB_TOKEN - registry authentication -# GITHUB_ACTOR - registry username (optional) -# - -set -e - -DBUILD_REF="${DBUILD_REF:-main}" - -# ── Locate dbuild ──────────────────────────────────────────────────── - -if [ -n "$DBUILD_PATH" ] && [ -d "$DBUILD_PATH/dbuild" ]; then - DBUILD_DIR="$DBUILD_PATH" -elif [ -d "../dbuild/dbuild" ]; then - DBUILD_DIR="$(cd ../dbuild && pwd)" -else - echo "Fetching dbuild ${DBUILD_REF}..." - mkdir -p /tmp/dbuild - fetch -qo /tmp/dbuild.tar.gz \ - "https://github.com/daemonless/dbuild/archive/${DBUILD_REF}.tar.gz" - tar -xzf /tmp/dbuild.tar.gz -C /tmp/dbuild --strip-components=1 - DBUILD_DIR="/tmp/dbuild" -fi - -export PYTHONPATH="$DBUILD_DIR" - -# ── Variant filter (optional) ──────────────────────────────────────── - -VARIANT_FLAG="" -if [ -n "$1" ]; then - VARIANT_FLAG="--variant $1" -fi - -# ── Delegate to dbuild ci-run ──────────────────────────────────────── - -exec python3 -m dbuild ci-run $VARIANT_FLAG diff --git a/dbuild/ci/__init__.py b/dbuild/ci/__init__.py index 205290d..6a2f78d 100644 --- a/dbuild/ci/__init__.py +++ b/dbuild/ci/__init__.py @@ -98,10 +98,6 @@ def detect() -> CIBase: from dbuild.ci.github import GitHubCI return GitHubCI() - if os.environ.get("CI_PIPELINE_ID"): - from dbuild.ci.woodpecker import WoodpeckerCI - return WoodpeckerCI() - if os.environ.get("GITLAB_CI"): from dbuild.ci.gitlab import GitLabCI return GitLabCI() diff --git a/dbuild/ci/woodpecker.py b/dbuild/ci/woodpecker.py deleted file mode 100644 index 06b028c..0000000 --- a/dbuild/ci/woodpecker.py +++ /dev/null @@ -1,113 +0,0 @@ -"""Woodpecker CI backend. - -Reads configuration from the CI_* environment variables that Woodpecker -injects into pipeline steps. Woodpecker does not have a native matrix -output mechanism, so ``output_matrix`` prints JSON to stdout for -consumption by downstream steps or external tooling. -""" - -from __future__ import annotations - -import json -import os -import sys -from typing import Any - -from dbuild import log -from dbuild.ci import CIBase - - -class WoodpeckerCI(CIBase): - """CI backend for Woodpecker CI.""" - - @staticmethod - def detect() -> bool: - """Return True when running inside a Woodpecker CI pipeline.""" - return os.environ.get("CI_PIPELINE_ID") is not None - - def get_token(self) -> str | None: - """Return the GITHUB_TOKEN from the environment. - - Woodpecker passes secrets as plain environment variables, so the - token is typically injected via the ``secrets:`` stanza in - ``.woodpecker.yaml``. - """ - return os.environ.get("GITHUB_TOKEN") - - def get_actor(self) -> str | None: - """Return the actor for registry login. - - Checks GITHUB_ACTOR first (if the secret is forwarded), then - falls back to the Woodpecker commit author. - """ - actor = os.environ.get("GITHUB_ACTOR") - if actor: - return actor - # Woodpecker provides CI_COMMIT_AUTHOR as a fallback. - author = os.environ.get("CI_COMMIT_AUTHOR") - if author: - return author - return None - - def is_pr(self) -> bool: - """Return True if this pipeline was triggered by a pull request.""" - return os.environ.get("CI_PIPELINE_EVENT") == "pull_request" - - def output_matrix(self, matrix: list[dict[str, Any]]) -> None: - """Print the build matrix as JSON to stdout. - - Woodpecker does not have a native matrix output mechanism like - GitHub Actions' ``$GITHUB_OUTPUT``. The JSON is printed to - stdout for consumption by wrapper scripts or external tooling. - """ - json.dump({"include": matrix}, sys.stdout, indent=2) - sys.stdout.write("\n") - sys.stdout.flush() - log.info(f"printed matrix with {len(matrix)} entries to stdout") - - def set_output(self, key: str, value: str) -> None: - """Print a key=value pair to stdout. - - Woodpecker does not have a structured output mechanism, so this - is best-effort for logging and downstream script consumption. - """ - sys.stdout.write(f"{key}={value}\n") - sys.stdout.flush() - - def get_commit_message(self) -> str: - """Return the commit message from Woodpecker's CI_COMMIT_MESSAGE.""" - return os.environ.get("CI_COMMIT_MESSAGE", "") - - def event_metadata(self) -> dict[str, Any]: - """Return metadata about the current pipeline event. - - Keys returned (when the corresponding env vars are set): - - ``sha``: The commit SHA. - - ``branch``: The branch being built. - - ``repo``: The repository identifier (e.g. ``daemonless/radarr``). - - ``run_url``: URL to the Woodpecker pipeline run. - - ``event``: The pipeline event type (push, pull_request, etc.). - """ - meta: dict[str, Any] = {} - - sha = os.environ.get("CI_COMMIT_SHA") - if sha: - meta["sha"] = sha - - branch = os.environ.get("CI_COMMIT_BRANCH") - if branch: - meta["branch"] = branch - - repo = os.environ.get("CI_REPO") - if repo: - meta["repo"] = repo - - pipeline_url = os.environ.get("CI_PIPELINE_URL") - if pipeline_url: - meta["run_url"] = pipeline_url - - event = os.environ.get("CI_PIPELINE_EVENT") - if event: - meta["event"] = event - - return meta diff --git a/dbuild/ci_run.py b/dbuild/ci_run.py index b54ab4b..e418293 100644 --- a/dbuild/ci_run.py +++ b/dbuild/ci_run.py @@ -1,8 +1,7 @@ """CI pipeline orchestration. -Replaces ``dbuild-ci.sh`` with a pure-Python implementation that calls -the build, test, push, and sbom modules directly. Runs the full -pipeline: build -> test -> push -> sbom. +Runs the full CI pipeline via Python calls to build, test, push, and sbom +(build -> test -> push -> sbom). On PR builds, push and sbom are skipped. Commit-message directives like ``[skip test]`` and ``[skip push]`` are honoured by the @@ -13,7 +12,7 @@ import argparse -from dbuild import build, log, prepare, push, sbom, test +from dbuild import build, log, push, sbom, test from dbuild import ci as ci_mod from dbuild.config import Config @@ -30,7 +29,6 @@ def run(cfg: Config, args: argparse.Namespace) -> int: * ``variant`` -- build only this tag (optional). * ``arch`` -- target architecture override (optional). - * ``prepare`` -- run ci-prepare first (optional). Returns ``0`` on success, non-zero on failure. """ @@ -39,12 +37,6 @@ def run(cfg: Config, args: argparse.Namespace) -> int: log.warn("Image is deprecated — skipping CI pipeline") return 0 - # Optional: run ci-prepare first - if getattr(args, "prepare", False): - rc = prepare.run(args) - if rc != 0: - return rc - # ── Build ──────────────────────────────────────────────────────── log.step("CI: Build") rc = build.run(cfg, args) diff --git a/dbuild/cli.py b/dbuild/cli.py index e34dde0..4c7ac9a 100644 --- a/dbuild/cli.py +++ b/dbuild/cli.py @@ -252,7 +252,7 @@ def _make_parser() -> argparse.ArgumentParser: ) detect_parser.add_argument( "--format", "-f", - choices=["json", "github", "woodpecker", "gitlab"], + choices=["json", "github", "gitlab"], default="json", dest="format", help="output format (default: json)", @@ -363,8 +363,8 @@ def _make_parser() -> argparse.ArgumentParser: init_parser.add_argument( "--category", metavar="CAT", - default="Apps", - help="application category (default: Apps)", + default=None, + help="application category (default: port mapping or DevOps)", ) init_parser.add_argument( "--type", @@ -405,12 +405,6 @@ def _make_parser() -> argparse.ArgumentParser: default=False, help="generate GitHub Actions workflow (.github/workflows/build.yaml)", ) - init_parser.add_argument( - "--woodpecker", - action="store_true", - default=False, - help="generate Woodpecker CI pipeline (.woodpecker.yaml)", - ) # -- lint -- sub.add_parser( @@ -523,20 +517,6 @@ def _make_parser() -> argparse.ArgumentParser: help="pull the image from registry if not found locally in storage", ) - # -- ci-prepare -- - ci_prepare_parser = sub.add_parser( - "ci-prepare", - help="prepare FreeBSD CI environment (install packages, ocijail, networking)", - description="Set up a FreeBSD CI runner with all build dependencies.", - ) - ci_prepare_parser.add_argument("--arch", **arch_kw) - ci_prepare_parser.add_argument( - "--compose", - action="store_true", - default=False, - help="also install podman-compose", - ) - # -- ci-test-env -- sub.add_parser( "ci-test-env", @@ -552,12 +532,6 @@ def _make_parser() -> argparse.ArgumentParser: ) ci_run_parser.add_argument("--variants", "--variant", **variant_kw) ci_run_parser.add_argument("--arch", **arch_kw) - ci_run_parser.add_argument( - "--prepare", - action="store_true", - default=False, - help="run ci-prepare before the pipeline", - ) # -- help -- help_parser = sub.add_parser( @@ -740,7 +714,7 @@ def _dispatch_prune(cfg: Config, args: argparse.Namespace) -> int: # Commands that run without loading project config _NO_CONFIG_COMMANDS: set[str] = { - "init", "ci-prepare", "ci-test-env", "lint", "screenshot", "logo", "help", "analyze", "audit", + "init", "ci-test-env", "lint", "screenshot", "logo", "help", "analyze", "audit", } @@ -783,9 +757,6 @@ def main(argv: list[str] | None = None) -> None: if args.command == "init": from dbuild import init rc = init.run(args) - elif args.command == "ci-prepare": - from dbuild import prepare - rc = prepare.run(args) elif args.command == "ci-test-env": from dbuild import ci_test rc = ci_test.run(args) diff --git a/dbuild/detect.py b/dbuild/detect.py index 6a9e375..f6cb106 100644 --- a/dbuild/detect.py +++ b/dbuild/detect.py @@ -1,7 +1,7 @@ """Variant auto-detection and CI matrix output. Reads config, generates the build matrix, and outputs it in a format -suitable for the detected CI system (GitHub Actions, Woodpecker, etc.) +suitable for the detected CI system (GitHub Actions, GitLab, etc.) or as plain JSON for local use. """ @@ -184,7 +184,7 @@ def _list_local_images(cfg: Config) -> tuple[list[dict], list[dict]]: def run(cfg: Config, args: argparse.Namespace) -> None: """Output detected build matrix. - When ``--format`` is ``github`` or ``woodpecker``, output is written + When ``--format`` is ``github`` or ``gitlab``, output is written via the CI backend. Otherwise, plain JSON is printed to stdout. """ matrix = _build_matrix(cfg, args) @@ -251,7 +251,7 @@ def run(cfg: Config, args: argparse.Namespace) -> None: backend.set_output(key, value) return - if fmt in ("woodpecker", "gitlab"): + if fmt == "gitlab": backend = ci_mod.detect() backend.output_matrix(matrix) return diff --git a/dbuild/fetch.py b/dbuild/fetch.py index 5874d40..35141f1 100644 --- a/dbuild/fetch.py +++ b/dbuild/fetch.py @@ -6,10 +6,30 @@ import shutil import subprocess import tempfile +import urllib.parse import urllib.request from dbuild import log +_ALLOWED_SCHEMES = frozenset({"http", "https"}) +DEFAULT_TIMEOUT = 30.0 +MAX_DOWNLOAD_BYTES = 50 * 1024 * 1024 + + +def _validate_http_url(url: str) -> None: + """Reject non-HTTP(S) URLs and URLs without a network host.""" + parsed = urllib.parse.urlparse(url) + if parsed.scheme.lower() not in _ALLOWED_SCHEMES or not parsed.netloc: + raise ValueError(f"Unsupported URL (expected http or https): {url}") + + +class _SafeRedirectHandler(urllib.request.HTTPRedirectHandler): + """Ensure HTTP redirects never jump to local or non-HTTP(S) schemes.""" + + def redirect_request(self, req, fp, code, msg, headers, newurl): + _validate_http_url(newurl) + return super().redirect_request(req, fp, code, msg, headers, newurl) + def detect_mime(path: str) -> str: """Return the MIME type of *path* using ``file --mime-type``.""" @@ -35,18 +55,37 @@ def github_raw_url(url: str) -> str: return url -def download_to_temp(url: str) -> str: +def download_to_temp( + url: str, + *, + timeout: float = DEFAULT_TIMEOUT, + max_bytes: int = MAX_DOWNLOAD_BYTES, +) -> str: """Download *url* to a temp file and return its path. + Only ``http`` and ``https`` URLs (including redirects) are allowed, bounded + by *timeout* seconds and *max_bytes* bytes. Raises on failure (after cleaning up the temp file). On success the caller owns the returned path and is responsible for unlinking it. """ + _validate_http_url(url) with tempfile.NamedTemporaryFile(delete=False, suffix=".tmp") as tf: tmp_path = tf.name try: + opener = urllib.request.build_opener(_SafeRedirectHandler()) req = urllib.request.Request(url, headers={"User-Agent": "dbuild/1.0"}) - with urllib.request.urlopen(req) as resp, open(tmp_path, "wb") as f: - shutil.copyfileobj(resp, f) + with opener.open(req, timeout=timeout) as resp, open(tmp_path, "wb") as f: + total = 0 + while True: + chunk = resp.read(65536) + if not chunk: + break + total += len(chunk) + if total > max_bytes: + raise ValueError( + f"Download exceeds {max_bytes // (1024 * 1024)} MB limit: {url}" + ) + f.write(chunk) except Exception: os.unlink(tmp_path) raise diff --git a/dbuild/init.py b/dbuild/init.py index 5a737be..b8158b8 100644 --- a/dbuild/init.py +++ b/dbuild/init.py @@ -21,7 +21,7 @@ from pathlib import Path from dbuild import log -from dbuild.config import DEFAULT_COMMUNITY +from dbuild.config import DEFAULT_COMMUNITY, VALID_CATEGORIES # Templates are co-located in the package _TEMPLATES_DIR = Path(__file__).parent / "templates" @@ -30,15 +30,27 @@ # which fills them from compose.yaml on every run; init must not bake the # values in, or compose.yaml stops being the single source of truth. _GENERATOR_KEYS = frozenset({"title", "description", "repo_url", "web_url", "category"}) +_COMPOSE_DQ_KEYS = frozenset({ + "title", "category", "description", + "upstream_url", "web_url", "freshports_url", "community", +}) _DEFAULT_PORT = 8080 _PORT_VARIANTS = "pkg,pkg-latest" +_PORT_TOKEN_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._+-]*$") +_APP_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9._-]*$") _FRESHPORTS_RE = re.compile(r"^https?://(?:www\.)?freshports\.org/([^/]+/[^/]+)/?$") _RC_VAR_RE = re.compile(r"\$\{(\w+)_port:?=\"?(\d{2,5})") # "localhost:8080", "http://127.0.0.1:9091/web", "https://:3000" _MSG_PORT_RE = re.compile(r"(?-]+:(\d{2,5})(?![\d.])") +def _yaml_dq(val: object) -> str: + """Escape a string rendered inside double-quoted YAML scalars.""" + text = " ".join(str(val).splitlines()).strip() + return text.replace("\\", "\\\\").replace('"', '\\"') + + # FreeBSD port category → daemonless category. # FreeBSD categories don't align with daemonless's vocabulary, so we map # best-effort. Unmapped categories fall back to None (triggers a warning). @@ -236,8 +248,14 @@ def _resolve_port_spec(spec: str, portsdir: Path | None) -> str | None: parts = [p for p in spec.split("/") if p] if len(parts) == 2: + if not all(_PORT_TOKEN_RE.match(p) for p in parts): + log.error( + f"invalid port '{spec}' — expected category/portname " + "(letters, digits, '.', '_', '+', '-')" + ) + return None return "/".join(parts) - if len(parts) != 1: + if len(parts) != 1 or not _PORT_TOKEN_RE.match(parts[0]): log.error( f"invalid port '{spec}' — expected category/portname " "(e.g. net-p2p/transmission), a FreshPorts URL, or a bare name" @@ -458,6 +476,13 @@ def _fetch_port_metadata( return _fetch_pkg_metadata(origin, want_run_deps) full_path = portsdir / origin + try: + if not full_path.resolve().is_relative_to(portsdir.resolve()): + log.error(f"invalid port path '{origin}' — resolves outside {portsdir}") + return None + except OSError: + log.error(f"invalid port path '{origin}'") + return None if not (full_path / "Makefile").is_file(): log.error(f"port not found: {full_path}") name = origin.split("/")[-1] @@ -671,10 +696,12 @@ def _render_template( return None content = src.read_text() + escape_dq = template_name == "compose.yaml" for key, val in context.items(): if generator and key in _GENERATOR_KEYS: continue - content = content.replace(f"{{{{ {key} }}}}", str(val)) + rendered = _yaml_dq(val) if (escape_dq and key in _COMPOSE_DQ_KEYS) else str(val) + content = content.replace(f"{{{{ {key} }}}}", rendered) if generator: return content @@ -900,6 +927,13 @@ def _next_steps(base: Path, app_name: str, review: list[str], from_port: bool) - def run(args: argparse.Namespace) -> int: """Scaffold a new dbuild project in the current directory.""" + raw_cat_arg = getattr(args, "category", None) + if raw_cat_arg is not None and raw_cat_arg not in VALID_CATEGORIES: + log.error( + f"invalid category '{raw_cat_arg}' (valid: {', '.join(VALID_CATEGORIES)})" + ) + return 1 + port_spec = getattr(args, "freebsd_port", None) flavors = [f.strip() for f in (getattr(args, "flavors", None) or "").split(",") if f.strip()] if flavors and not port_spec: @@ -921,12 +955,19 @@ def run(args: argparse.Namespace) -> int: return 1 port_meta = fetched - app_name = args.name or port_meta.get("name") or Path.cwd().name + app_name = str(args.name or port_meta.get("name") or Path.cwd().name) + if not _APP_NAME_RE.match(app_name): + log.error( + f"invalid application name '{app_name}' " + "(use lowercase letters, digits, '.', '_', or '-'; pass --name to override)" + ) + return 1 + # node_exporter -> Node Exporter; a brand's own casing is a --title job title = args.title or " ".join(w.capitalize() for w in app_name.split("_")) - category_from_arg = bool(args.category and args.category != "Apps") + category_from_arg = raw_cat_arg is not None category = ( - args.category if category_from_arg + raw_cat_arg if category_from_arg else (port_meta.get("category") or "DevOps") ) port_arg = getattr(args, "port", None) @@ -1014,8 +1055,6 @@ def run(args: argparse.Namespace) -> int: "setup.sh", daemonless / "init.d" / f"20-{app_name}", context, dry_run, executable=True, ) - if getattr(args, "woodpecker", False): - created += _scaffold("woodpecker.yaml", base / ".woodpecker.yaml", context, dry_run) if getattr(args, "github", False): created += _scaffold( "github-workflow.yaml", diff --git a/dbuild/prepare.py b/dbuild/prepare.py deleted file mode 100644 index 79e3497..0000000 --- a/dbuild/prepare.py +++ /dev/null @@ -1,151 +0,0 @@ -"""FreeBSD CI environment preparation. - -Sets up the build environment for CI runners: configures the pkg repo, -installs required packages, installs the patched ocijail, cleans stale -container state, and configures networking (pf + IP forwarding). - -Each step is idempotent and safe to re-run. Requires root. -""" - -from __future__ import annotations - -import argparse -import os -import platform -import subprocess - -from dbuild import ci as ci_mod -from dbuild import log -from dbuild.ci.local import LocalCI - -# ── Constants ──────────────────────────────────────────────────────── - -_OCIJAIL_URL_TEMPLATE = ( - "https://github.com/daemonless/freebsd-ports/releases/download/" - "v0.4.0-patched/ocijail-0.4.0_3-{arch}.pkg" -) - -_PKG_LIST = [ - "podman", "skopeo", "buildah", "trivy", - "python3", "py312-pyyaml", -] - -_COMPOSE_PKG = "podman-compose" - -# ── Helpers ────────────────────────────────────────────────────────── - - -def _run(cmd: list[str], **kwargs) -> subprocess.CompletedProcess: - """Run a command, logging it first. Raises on failure.""" - log.info(f"$ {' '.join(cmd)}") - return subprocess.run(cmd, check=True, **kwargs) - - -def _detect_arch() -> str: - """Detect the FreeBSD architecture label (amd64 / aarch64).""" - machine = platform.machine() - mapping = { - "amd64": "amd64", - "x86_64": "amd64", - "arm64": "aarch64", - "aarch64": "aarch64", - } - return mapping.get(machine, machine) - - -# ── Steps ──────────────────────────────────────────────────────────── - - -def configure_pkg_repo() -> None: - """Write /etc/pkg/FreeBSD.conf for the 'latest' package set.""" - log.step("Configuring pkg repository") - os.makedirs("/etc/pkg", exist_ok=True) - with open("/etc/pkg/FreeBSD.conf", "w") as f: - f.write('FreeBSD: { url: "http://pkg.FreeBSD.org/${ABI}/latest" }\n') - _run(["pkg", "update", "-f"]) - - -def install_packages(*, compose: bool = False) -> None: - """Install required packages via pkg.""" - log.step("Installing packages") - pkgs = list(_PKG_LIST) - if compose: - pkgs.append(_COMPOSE_PKG) - _run(["pkg", "install", "-y", *pkgs]) - - -def install_ocijail(*, arch: str | None = None) -> None: - """Fetch and install the patched ocijail package.""" - log.step("Installing patched ocijail") - if arch is None: - arch = _detect_arch() - url = _OCIJAIL_URL_TEMPLATE.format(arch=arch) - pkg_path = "/tmp/ocijail.pkg" - _run(["fetch", "-qo", pkg_path, url]) - _run(["pkg", "install", "-fy", pkg_path]) - - -def cleanup_containers() -> None: - """Remove stale container storage directories.""" - log.step("Cleaning container storage") - for path in ("/var/db/containers", "/var/lib/containers"): - _run(["rm", "-rf", path]) - - -def configure_networking() -> None: - """Load pf kernel module and enable IP forwarding.""" - log.step("Configuring networking") - _run(["kldload", "-n", "pf"]) - _run(["sysctl", "net.inet.ip.forwarding=1"]) - - -# ── Public API ─────────────────────────────────────────────────────── - - -def run(args: argparse.Namespace) -> int: - """Run the full CI environment preparation. - - Parameters - ---------- - args: - CLI arguments. Recognised attributes: - - * ``arch`` -- target architecture override (optional). - * ``compose`` -- install podman-compose (optional). - - Returns ``0`` on success, ``1`` on failure. - """ - if os.geteuid() != 0: - log.error("ci-prepare must run as root") - return 1 - - # Warn when running outside CI (bare metal / production host) - backend = ci_mod.detect() - if isinstance(backend, LocalCI): - log.warn("No CI environment detected -- running on bare metal") - log.warn("This will: install packages, overwrite /etc/pkg/FreeBSD.conf,") - log.warn(" wipe container storage, load pf, enable IP forwarding") - try: - answer = input("[warn] Continue? [y/N] ") - except (EOFError, KeyboardInterrupt): - print() - return 1 - if answer.strip().lower() not in ("y", "yes"): - log.info("Aborted") - return 1 - - arch: str | None = getattr(args, "arch", None) - compose: bool = getattr(args, "compose", False) - - try: - configure_pkg_repo() - install_packages(compose=compose) - install_ocijail(arch=arch) - cleanup_containers() - configure_networking() - except subprocess.CalledProcessError as exc: - log.error(f"Command failed: {exc}") - return 1 - - log.success("CI environment ready") - return 0 diff --git a/dbuild/registry/dockerhub.py b/dbuild/registry/dockerhub.py index 1cf2072..de9a4bd 100644 --- a/dbuild/registry/dockerhub.py +++ b/dbuild/registry/dockerhub.py @@ -1,15 +1,11 @@ """Docker Hub registry backend. Inherits from :class:`~dbuild.registry.generic.GenericRegistry` and adds -support for Docker Hub mirroring (via ``skopeo copy``) and repository -description updates. +support for Docker Hub mirroring via ``skopeo copy``. """ from __future__ import annotations -import json -import subprocess - from dbuild import log, podman from dbuild.registry.generic import GenericRegistry @@ -31,65 +27,3 @@ def mirror_from(self, src: str, dest: str) -> None: """ log.info(f"Mirroring {src} -> {dest} (Docker Hub)") self.copy(src, dest) - - def update_description( - self, - repo: str, - description: str, - *, - username: str, - password: str, - ) -> None: - """Update the Docker Hub repository description. - - Uses the Docker Hub API v2 to PATCH the repository description. - Requires Docker Hub credentials (not a GHCR token). - """ - # Obtain a JWT from Docker Hub. - login_payload = json.dumps({ - "username": username, - "password": password, - }) - login_proc = subprocess.run( - [ - "fetch", "-qo", "-", - "--method", "POST", - "--header", "Content-Type: application/json", - "--body", login_payload, - "https://hub.docker.com/v2/users/login/", - ], - capture_output=True, - text=True, - check=False, - ) - if login_proc.returncode != 0: - log.warn(f"Docker Hub login for description update failed: {login_proc.stderr.strip()}") - return - try: - jwt = json.loads(login_proc.stdout).get("token") - except (json.JSONDecodeError, AttributeError): - log.warn("Could not parse Docker Hub login response") - return - if not jwt: - log.warn("No token in Docker Hub login response") - return - - # PATCH the description. - patch_payload = json.dumps({"description": description}) - patch_proc = subprocess.run( - [ - "fetch", "-qo", "-", - "--method", "PATCH", - "--header", "Content-Type: application/json", - "--header", f"Authorization: JWT {jwt}", - "--body", patch_payload, - f"https://hub.docker.com/v2/repositories/{repo}/", - ], - capture_output=True, - text=True, - check=False, - ) - if patch_proc.returncode != 0: - log.warn(f"Docker Hub description update failed: {patch_proc.stderr.strip()}") - else: - log.success(f"Updated Docker Hub description for {repo}") diff --git a/dbuild/templates/woodpecker.yaml b/dbuild/templates/woodpecker.yaml deleted file mode 100644 index b242a18..0000000 --- a/dbuild/templates/woodpecker.yaml +++ /dev/null @@ -1,34 +0,0 @@ -# Woodpecker CI workflow for building FreeBSD container images with dbuild. -# -# Override the bootstrap step by placing .daemonless/bootstrap.sh in your repo. -# Commit message directives: [skip test], [skip push], [skip sbom] - -steps: - - name: build - image: /bin/sh - commands: - - | - DBUILD_REF="${DBUILD_REF:-v1.9.0}" - if [ -n "$DBUILD_PATH" ] && [ -d "$DBUILD_PATH/dbuild" ]; then - export PYTHONPATH="$DBUILD_PATH" - elif [ -d "../dbuild/dbuild" ]; then - export PYTHONPATH="$(cd ../dbuild && pwd)" - else - if [ -f .daemonless/bootstrap.sh ]; then - sh .daemonless/bootstrap.sh - else - fetch -qo /tmp/bootstrap.sh \ - "https://raw.githubusercontent.com/daemonless/dbuild/${DBUILD_REF}/bootstrap.sh" - sh /tmp/bootstrap.sh - fi - export PYTHONPATH="${DBUILD_DIR:-/tmp/dbuild}" - fi - - python3 -m dbuild ci-run - -when: - - event: push - branch: main - path: - exclude: ["*.md", "docs/**", "LICENSE", ".gitignore"] - - event: manual diff --git a/dbuild/upstream_assets.py b/dbuild/upstream_assets.py index f3bd92e..a3f5372 100644 --- a/dbuild/upstream_assets.py +++ b/dbuild/upstream_assets.py @@ -133,7 +133,7 @@ def _stem_from_url(url: str) -> str: stem = Path(basename).stem if basename else "" if not stem or stem in ("raw", "blob", "main", "master"): stem = "" - safe = "".join(c if c.isalnum() or c in "-_." else "_" for c in stem) + safe = "".join(c if c.isalnum() or c in "-_." else "_" for c in stem).strip(".") return safe or "screenshot" @@ -156,8 +156,9 @@ def download_screenshot(url: str, repo_dir: Path | None = None) -> int: mime = fetch.detect_mime(tmp_path) ext = _SCREENSHOT_MIME_EXT.get(mime) if not ext: - log.warn(f"Unrecognised MIME type '{mime}' — defaulting to .png") - ext = ".png" + log.error(f"Unsupported screenshot format '{mime}'") + os.unlink(tmp_path) + return 1 log.info(f"Detected type: {mime} → {ext}") for msg in screenshot_warnings(tmp_path, ext): @@ -181,6 +182,7 @@ def download_screenshot(url: str, repo_dir: Path | None = None) -> int: counter += 1 shutil.move(tmp_path, str(dest)) + os.chmod(dest, 0o644) log.success(f"Saved: {dest.relative_to(base)}") return 0 @@ -195,7 +197,7 @@ def process_logo(source: str, repo_dir: Path | None = None, dark: bool = False) logo_dir = base / ".daemonless" logo_prefix = "logo-dark" if dark else "logo" - is_url = source.startswith(("http://", "https://")) + is_url = source.lower().startswith(("http://", "https://")) local_file = Path(source) if not is_url else None if local_file: @@ -251,6 +253,7 @@ def process_logo(source: str, repo_dir: Path | None = None, dark: bool = False) try: shutil.copy2(src_path, str(dest)) + os.chmod(dest, 0o644) log.success(f"Saved: {dest.relative_to(base)}") except Exception as e: log.error(f"Failed to copy logo file to destination: {e}") diff --git a/docs/dbuild.1 b/docs/dbuild.1 index f9e18ed..d861277 100644 --- a/docs/dbuild.1 +++ b/docs/dbuild.1 @@ -1,4 +1,4 @@ -.TH DBUILD 1 "2026-11-16" "dbuild 1.13.1" "User Commands" +.TH DBUILD 1 "2026-11-24" "dbuild 1.13.1" "User Commands" .SH NAME dbuild \- FreeBSD OCI container image build tool .SH SYNOPSIS @@ -125,20 +125,6 @@ show this help message and exit write here instead of stdout .RE .TP -\fBci-prepare\fR -Set up a FreeBSD CI runner with all build dependencies. -.RS -.TP -\fB-h\fR, \fB--help\fR -show this help message and exit -.TP -\fB--arch\fR -override target architecture (e.g. amd64, aarch64) -.TP -\fB--compose\fR -also install podman-compose -.RE -.TP \fBci-run\fR Run the complete CI/CD pipeline for all (or selected) variants. .RS @@ -151,9 +137,6 @@ filter to one or more variants by tag (comma-separated, e.g. pkg,pkg-latest) .TP \fB--arch\fR override target architecture (e.g. amd64, aarch64) -.TP -\fB--prepare\fR -run ci-prepare before the pipeline .RE .TP \fBci-test-env\fR @@ -228,7 +211,7 @@ application name (e.g. radarr) human-readable title (e.g. Radarr) .TP \fB--category\fR -application category (default: Apps) +application category (default: port mapping or DevOps) .TP \fB--type\fR application type (default: generic) @@ -247,9 +230,6 @@ show what would be created without writing to disk .TP \fB--github\fR generate GitHub Actions workflow (.github/workflows/build.yaml) -.TP -\fB--woodpecker\fR -generate Woodpecker CI pipeline (.woodpecker.yaml) .RE .TP \fBlint\fR @@ -401,12 +381,12 @@ The primary source of truth for metadata and documentation. \fI.daemonless/config.yaml\fR Project-specific build and test overrides. .TP -\fI/usr/local/etc/daemonless.yaml\fR +\fI$PREFIX/etc/daemonless.yaml\fR Optional host-local defaults, including pkg_cache_url for local pkg-cache injection. .SH GLOBAL CONFIGURATION -The \fI/usr/local/etc/daemonless.yaml\fR file is an optional host-local config file for settings that apply on this builder, not in every image repo. To use a local pkg cache, set \fIpkg_cache_url\fR. dbuild injects that value into builds as \fIPKG_CACHE_URL\fR, and opt-in Containerfiles can use it to point FreeBSD pkg at the local cache during build. If the file or key is missing, nothing is injected. +The \fI$PREFIX/etc/daemonless.yaml\fR file is an optional host-local config file for settings that apply on this builder, not in every image repo. To use a local pkg cache, set \fIpkg_cache_url\fR. dbuild injects that value into builds as \fIPKG_CACHE_URL\fR, and opt-in Containerfiles can use it to point FreeBSD pkg at the local cache during build. If the file or key is missing, nothing is injected. .PP -Example \fI/usr/local/etc/daemonless.yaml\fR: +Example \fI$PREFIX/etc/daemonless.yaml\fR: .IP .nf pkg_cache_url: pkg-cache.example.lan:8080 diff --git a/tests/test_ci.py b/tests/test_ci.py index 004318f..b5c9b29 100644 --- a/tests/test_ci.py +++ b/tests/test_ci.py @@ -125,10 +125,10 @@ def test_github(self): self.assertIsInstance(ci, GitHubCI) @patch.dict("os.environ", {"CI_PIPELINE_ID": "123"}, clear=True) - def test_woodpecker(self): - from dbuild.ci.woodpecker import WoodpeckerCI + def test_ci_pipeline_id_falls_back_to_local(self): + from dbuild.ci.local import LocalCI ci = detect() - self.assertIsInstance(ci, WoodpeckerCI) + self.assertIsInstance(ci, LocalCI) @patch.dict("os.environ", {"GITLAB_CI": "true"}, clear=True) def test_gitlab(self): @@ -213,38 +213,6 @@ def test_set_output_multiline(self): os.unlink(output_file) -class TestWoodpeckerCI(unittest.TestCase): - """Tests for WoodpeckerCI backend.""" - - @patch.dict("os.environ", {"CI_PIPELINE_ID": "42"}) - def test_detect(self): - from dbuild.ci.woodpecker import WoodpeckerCI - self.assertTrue(WoodpeckerCI.detect()) - - @patch.dict("os.environ", {}, clear=True) - def test_detect_false(self): - from dbuild.ci.woodpecker import WoodpeckerCI - self.assertFalse(WoodpeckerCI.detect()) - - @patch.dict("os.environ", {"CI_COMMIT_MESSAGE": "fix: stuff [skip test]"}) - def test_get_commit_message(self): - from dbuild.ci.woodpecker import WoodpeckerCI - ci = WoodpeckerCI() - self.assertEqual(ci.get_commit_message(), "fix: stuff [skip test]") - - @patch.dict("os.environ", {"CI_PIPELINE_EVENT": "pull_request"}) - def test_is_pr(self): - from dbuild.ci.woodpecker import WoodpeckerCI - ci = WoodpeckerCI() - self.assertTrue(ci.is_pr()) - - @patch.dict("os.environ", {"CI_PIPELINE_EVENT": "push"}) - def test_is_not_pr(self): - from dbuild.ci.woodpecker import WoodpeckerCI - ci = WoodpeckerCI() - self.assertFalse(ci.is_pr()) - - class TestGitLabCI(unittest.TestCase): """Tests for GitLabCI backend.""" diff --git a/tests/test_ci_run.py b/tests/test_ci_run.py index 2988a01..f43cdb4 100644 --- a/tests/test_ci_run.py +++ b/tests/test_ci_run.py @@ -19,7 +19,7 @@ def _make_cfg() -> Config: def _make_args(**overrides) -> argparse.Namespace: - defaults = dict(variant=None, arch=None, prepare=False) + defaults = dict(variant=None, arch=None) defaults.update(overrides) return argparse.Namespace(**defaults) @@ -96,42 +96,6 @@ def test_build_failure_stops_early(self, mock_build): self.assertEqual(rc, 1) - @patch("dbuild.ci_run.ci_mod.detect") - @patch("dbuild.ci_run.sbom") - @patch("dbuild.ci_run.push") - @patch("dbuild.ci_run.test") - @patch("dbuild.ci_run.build") - @patch("dbuild.ci_run.prepare") - def test_prepare_flag(self, mock_prepare, mock_build, mock_test, - mock_push, mock_sbom, mock_ci_detect): - """--prepare runs ci-prepare before the pipeline.""" - mock_prepare.run.return_value = 0 - mock_build.run.return_value = None - mock_test.run.return_value = 0 - mock_push.run.return_value = None - mock_sbom.run.return_value = None - ci_backend = MagicMock() - ci_backend.is_pr.return_value = False - mock_ci_detect.return_value = ci_backend - - cfg = _make_cfg() - args = _make_args(prepare=True) - rc = run(cfg, args) - - self.assertEqual(rc, 0) - mock_prepare.run.assert_called_once() - - @patch("dbuild.ci_run.prepare") - def test_prepare_failure_stops_pipeline(self, mock_prepare): - """When ci-prepare fails, pipeline stops.""" - mock_prepare.run.return_value = 1 - - cfg = _make_cfg() - args = _make_args(prepare=True) - rc = run(cfg, args) - - self.assertEqual(rc, 1) - if __name__ == "__main__": unittest.main() diff --git a/tests/test_cli.py b/tests/test_cli.py index f07a809..0a2ab22 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -61,22 +61,10 @@ def test_ci_test_env_command(self): args = self.parser.parse_args(["ci-test-env"]) self.assertEqual(args.command, "ci-test-env") - def test_ci_prepare_command(self): - args = self.parser.parse_args(["ci-prepare"]) - self.assertEqual(args.command, "ci-prepare") - def test_ci_run_command(self): args = self.parser.parse_args(["ci-run"]) self.assertEqual(args.command, "ci-run") - def test_ci_prepare_arch(self): - args = self.parser.parse_args(["ci-prepare", "--arch", "aarch64"]) - self.assertEqual(args.arch, "aarch64") - - def test_ci_prepare_compose(self): - args = self.parser.parse_args(["ci-prepare", "--compose"]) - self.assertTrue(args.compose) - def test_ci_run_variant(self): args = self.parser.parse_args(["ci-run", "--variant", "pkg"]) self.assertEqual(args.variant, "pkg") @@ -85,9 +73,20 @@ def test_ci_run_arch(self): args = self.parser.parse_args(["ci-run", "--arch", "amd64"]) self.assertEqual(args.arch, "amd64") - def test_ci_run_prepare_flag(self): - args = self.parser.parse_args(["ci-run", "--prepare"]) - self.assertTrue(args.prepare) + def test_retired_woodpecker_and_prepare_rejected(self): + for argv in ( + ["ci-prepare"], + ["ci-run", "--prepare"], + ["init", "--woodpecker"], + ["detect", "--format", "woodpecker"], + ): + with ( + self.subTest(argv=argv), + unittest.mock.patch("sys.stderr"), + self.assertRaises(SystemExit) as ctx, + ): + self.parser.parse_args(argv) + self.assertEqual(ctx.exception.code, 2) # ── Global options ──────────────────────────────────────────────── @@ -169,9 +168,9 @@ def test_init_github_flag(self): args = self.parser.parse_args(["init", "--github"]) self.assertTrue(args.github) - def test_init_woodpecker_flag(self): - args = self.parser.parse_args(["init", "--woodpecker"]) - self.assertTrue(args.woodpecker) + def test_init_category_default_none(self): + args = self.parser.parse_args(["init"]) + self.assertIsNone(args.category) # ── Help options ────────────────────────────────────────────────── diff --git a/tests/test_fetch.py b/tests/test_fetch.py index d88e8b2..bef1387 100644 --- a/tests/test_fetch.py +++ b/tests/test_fetch.py @@ -1,8 +1,35 @@ -"""Tests for dbuild.fetch shared download/MIME helpers.""" +"""Tests for dbuild.fetch shared download/MIME helpers and upstream_assets.""" +from __future__ import annotations + +import http.server +import os +import stat +import tempfile +import threading import unittest +import urllib.error +from pathlib import Path +from unittest.mock import patch + +from dbuild import fetch, upstream_assets + + +class _MockServer: + """Minimal localhost HTTP server for download_to_temp redirect and cap tests.""" -from dbuild import fetch + def __init__(self, handler_cls): + self._srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler_cls) + self.port = self._srv.server_address[1] + self._thread = threading.Thread(target=self._srv.serve_forever, daemon=True) + + def __enter__(self): + self._thread.start() + return self + + def __exit__(self, *args): + self._srv.shutdown() + self._srv.server_close() class TestGithubRawUrl(unittest.TestCase): @@ -26,5 +53,134 @@ def test_github_non_blob_unchanged(self): self.assertEqual(fetch.github_raw_url(url), url) +class TestDownloadToTemp(unittest.TestCase): + def test_rejects_non_http_schemes(self): + for bad in ("file:///etc/passwd", "ftp://example.com/img.png", "/etc/passwd", "https://"): + with self.subTest(url=bad), self.assertRaises(ValueError): + fetch.download_to_temp(bad) + + def test_downloads_valid_http_response(self): + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + body = b"PNG-BYTES" + self.send_response(200) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + with _MockServer(Handler) as srv: + tmp = fetch.download_to_temp(f"http://127.0.0.1:{srv.port}/img.png") + try: + self.assertEqual(Path(tmp).read_bytes(), b"PNG-BYTES") + finally: + os.unlink(tmp) + + def test_rejects_redirect_to_ftp_and_file_schemes(self): + for target, exc_types in ( + ("ftp://example.com/evil", ValueError), + ("file:///etc/passwd", (ValueError, urllib.error.HTTPError)), + ): + class Handler(http.server.BaseHTTPRequestHandler): + location = target + + def do_GET(self): + self.send_response(302) + self.send_header("Location", self.location) + self.end_headers() + + def log_message(self, *args): + pass + + with ( + self.subTest(target=target), + _MockServer(Handler) as srv, + self.assertRaises(exc_types), + ): + fetch.download_to_temp(f"http://127.0.0.1:{srv.port}/evil") + + def test_enforces_max_bytes_limit(self): + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + body = b"A" * 2048 + self.send_response(200) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + with _MockServer(Handler) as srv, self.assertRaises(ValueError): + fetch.download_to_temp(f"http://127.0.0.1:{srv.port}/big", max_bytes=1024) + + +class TestUpstreamAssets(unittest.TestCase): + def test_stem_from_url_sanitizes_dots(self): + self.assertEqual(upstream_assets._stem_from_url("https://example.com/.."), "screenshot") + self.assertEqual(upstream_assets._stem_from_url("https://example.com/."), "screenshot") + self.assertEqual(upstream_assets._stem_from_url("https://example.com/screen.png"), "screen") + + def test_download_screenshot_rejects_unknown_mime_and_cleans_temp(self): + with tempfile.TemporaryDirectory() as d: + repo = Path(d) + (repo / ".daemonless").mkdir() + with tempfile.NamedTemporaryFile(delete=False) as tmp: + tmp.write(b"not an image") + tmp_path = tmp.name + + with ( + patch("dbuild.fetch.download_to_temp", return_value=tmp_path), + patch("dbuild.fetch.detect_mime", return_value="text/html"), + ): + rc = upstream_assets.download_screenshot("https://example.com/shot.png", repo) + + self.assertEqual(rc, 1) + self.assertFalse(Path(tmp_path).exists()) + self.assertFalse((repo / ".daemonless" / "screenshots").exists()) + + def test_download_screenshot_sets_0644_permissions(self): + with tempfile.TemporaryDirectory() as d: + repo = Path(d) + (repo / ".daemonless").mkdir() + with tempfile.NamedTemporaryFile(delete=False) as tmp: + tmp.write(b"\x89PNG\r\n\x1a\n") + tmp_path = tmp.name + os.chmod(tmp_path, 0o600) + + with ( + patch("dbuild.fetch.download_to_temp", return_value=tmp_path), + patch("dbuild.fetch.detect_mime", return_value="image/png"), + ): + rc = upstream_assets.download_screenshot("https://example.com/shot.png", repo) + + saved = repo / ".daemonless" / "screenshots" / "shot.png" + self.assertEqual(rc, 0) + self.assertTrue(saved.exists()) + self.assertEqual(stat.S_IMODE(saved.stat().st_mode), 0o644) + + def test_process_logo_sets_0644_permissions(self): + with tempfile.TemporaryDirectory() as d: + repo = Path(d) + (repo / ".daemonless").mkdir() + with tempfile.NamedTemporaryFile(delete=False) as tmp: + tmp.write(b"") + tmp_path = tmp.name + os.chmod(tmp_path, 0o600) + + with ( + patch("dbuild.fetch.download_to_temp", return_value=tmp_path), + patch("dbuild.fetch.detect_mime", return_value="image/svg+xml"), + ): + rc = upstream_assets.process_logo("https://example.com/logo.svg", repo) + + saved = repo / ".daemonless" / "logo.svg" + self.assertEqual(rc, 0) + self.assertTrue(saved.exists()) + self.assertEqual(stat.S_IMODE(saved.stat().st_mode), 0o644) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_init.py b/tests/test_init.py index 799c64a..249f9ea 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -8,6 +8,8 @@ from pathlib import Path from unittest.mock import patch +import yaml + from dbuild import init from dbuild.init import _build_variants_block, run @@ -16,13 +18,12 @@ def _base_args(**overrides): args = argparse.Namespace( name="testapp", title="TestApp", - category="Apps", + category=None, type="generic", port=8080, variants="latest", community=None, dry_run=False, - woodpecker=False, github=False, freebsd_port=None, flavors=None, @@ -305,6 +306,37 @@ def test_bare_name_falls_back_to_pkg_origin(self): with patch("dbuild.init._pkg_rquery", return_value="net-p2p/transmission-components"): self.assertEqual(init._resolve_port_spec("transmission-daemon", None), "net-p2p/transmission-components") + def test_rejects_traversal_and_globs(self): + with tempfile.TemporaryDirectory() as d: + root = Path(d) + _fake_port(root, "www/gitea", {}) + for bad in ( + "../evil", + "www/..", + "../../tmp/evil", + "foo/*", + "www/gitea*", + "gite?", + "[a-z]*", + f"{root}/../evil", + "https://www.freshports.org/net-p2p/..", + ): + with self.subTest(bad=bad): + self.assertIsNone(init._resolve_port_spec(bad, root)) + + def test_fetch_port_metadata_rejects_symlink_escape(self): + with tempfile.TemporaryDirectory() as d: + tmp = Path(d) + ports = tmp / "ports" + (ports / "Mk").mkdir(parents=True) + outside = tmp / "outside" + outside.mkdir() + (outside / "Makefile").write_text("PORTNAME=evil\n") + (ports / "www").mkdir() + (ports / "www" / "escape").symlink_to(outside) + with patch("dbuild.init._portsdir", return_value=ports): + self.assertIsNone(init._fetch_port_metadata("www/escape")) + class TestRcScript(unittest.TestCase): """_rc_script_info finds the daemon through rc.d conventions.""" @@ -517,5 +549,72 @@ def test_on(self): self.assertNotRegex(config, r"\n[ \t]+\n") +class TestInputValidationAndYamlEscaping(unittest.TestCase): + """Validation of --name / --category and YAML escaping in compose.yaml.""" + + def test_invalid_category_rejected_cleanly(self): + for bad in ("Apps", "NotACategory", "media"): + with ( + self.subTest(category=bad), + tempfile.TemporaryDirectory() as d, + patch("dbuild.init.Path.cwd", return_value=Path(d)), + ): + rc = run(_base_args(category=bad)) + self.assertEqual(rc, 1) + self.assertEqual(list(Path(d).iterdir()), []) + + def test_valid_category_accepted_and_none_defaults_to_devops(self): + with tempfile.TemporaryDirectory() as d, patch("dbuild.init.Path.cwd", return_value=Path(d)): + self.assertEqual(run(_base_args(category="Networking")), 0) + compose = yaml.safe_load((Path(d) / "compose.yaml").read_text()) + self.assertEqual(compose["x-daemonless"]["category"], "Networking") + + with tempfile.TemporaryDirectory() as d, patch("dbuild.init.Path.cwd", return_value=Path(d)): + self.assertEqual(run(_base_args(category=None)), 0) + compose = yaml.safe_load((Path(d) / "compose.yaml").read_text()) + self.assertEqual(compose["x-daemonless"]["category"], "DevOps") + + def test_invalid_app_name_rejected(self): + for bad in ("bad name", "../evil", "BadCaps", "-leading"): + with ( + self.subTest(name=bad), + tempfile.TemporaryDirectory() as d, + patch("dbuild.init.Path.cwd", return_value=Path(d)), + ): + rc = run(_base_args(name=bad)) + self.assertEqual(rc, 1) + self.assertEqual(list(Path(d).iterdir()), []) + + def test_compose_yaml_escapes_quotes_backslashes_and_newlines(self): + meta = dict( + _PORT_META, + name="quotetest", + description='Fast "quote" tool\nwith \\backslash', + category="DevOps", + ) + with ( + tempfile.TemporaryDirectory() as d, + patch("dbuild.init.Path.cwd", return_value=Path(d)), + patch("dbuild.init._fetch_port_metadata", return_value=meta), + ): + rc = run(_base_args( + name=None, + title='App "One" \\ Test', + freebsd_port="sysutils/quotetest", + community='Discord:"https://discord.gg/test"', + )) + self.assertEqual(rc, 0) + compose = yaml.safe_load((Path(d) / "compose.yaml").read_text()) + self.assertEqual(compose["x-daemonless"]["title"], 'App "One" \\ Test') + self.assertEqual( + compose["x-daemonless"]["description"], + 'Fast "quote" tool with \\backslash', + ) + self.assertEqual( + compose["x-daemonless"]["community"], + 'Discord:"https://discord.gg/test"', + ) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_prepare.py b/tests/test_prepare.py deleted file mode 100644 index a497fb2..0000000 --- a/tests/test_prepare.py +++ /dev/null @@ -1,174 +0,0 @@ -"""Unit tests for dbuild.prepare.""" - -from __future__ import annotations - -import argparse -import subprocess -import unittest -from unittest.mock import MagicMock, patch - -from dbuild import prepare -from dbuild.ci.local import LocalCI - - -class TestConfigurePkgRepo(unittest.TestCase): - """Tests for configure_pkg_repo().""" - - @patch("dbuild.prepare._run") - @patch("builtins.open", unittest.mock.mock_open()) - @patch("os.makedirs") - def test_writes_conf_and_updates(self, mock_makedirs, mock_run): - prepare.configure_pkg_repo() - mock_makedirs.assert_called_once_with("/etc/pkg", exist_ok=True) - mock_run.assert_called_once_with(["pkg", "update", "-f"]) - - -class TestInstallPackages(unittest.TestCase): - """Tests for install_packages().""" - - @patch("dbuild.prepare._run") - def test_default_packages(self, mock_run): - prepare.install_packages() - args = mock_run.call_args[0][0] - self.assertEqual(args[:3], ["pkg", "install", "-y"]) - self.assertIn("podman", args) - self.assertIn("trivy", args) - self.assertNotIn("podman-compose", args) - - @patch("dbuild.prepare._run") - def test_compose_flag(self, mock_run): - prepare.install_packages(compose=True) - args = mock_run.call_args[0][0] - self.assertIn("podman-compose", args) - - -class TestInstallOcijail(unittest.TestCase): - """Tests for install_ocijail().""" - - @patch("dbuild.prepare._run") - def test_fetches_correct_url(self, mock_run): - prepare.install_ocijail(arch="amd64") - calls = mock_run.call_args_list - # First call: fetch - fetch_args = calls[0][0][0] - self.assertEqual(fetch_args[0], "fetch") - self.assertIn("amd64", fetch_args[-1]) - # Second call: pkg install - pkg_args = calls[1][0][0] - self.assertEqual(pkg_args[:3], ["pkg", "install", "-fy"]) - - @patch("dbuild.prepare._run") - def test_aarch64_url(self, mock_run): - prepare.install_ocijail(arch="aarch64") - fetch_url = mock_run.call_args_list[0][0][0][-1] - self.assertIn("aarch64", fetch_url) - - -class TestCleanupContainers(unittest.TestCase): - """Tests for cleanup_containers().""" - - @patch("dbuild.prepare._run") - def test_removes_both_dirs(self, mock_run): - prepare.cleanup_containers() - self.assertEqual(mock_run.call_count, 2) - mock_run.assert_any_call(["rm", "-rf", "/var/db/containers"]) - mock_run.assert_any_call(["rm", "-rf", "/var/lib/containers"]) - - -class TestConfigureNetworking(unittest.TestCase): - """Tests for configure_networking().""" - - @patch("dbuild.prepare._run") - def test_kldload_and_sysctl(self, mock_run): - prepare.configure_networking() - mock_run.assert_any_call(["kldload", "-n", "pf"]) - mock_run.assert_any_call(["sysctl", "net.inet.ip.forwarding=1"]) - - -class TestRun(unittest.TestCase): - """Tests for prepare.run().""" - - @patch("os.geteuid", return_value=1000) - def test_not_root_fails(self, _mock_euid): - args = argparse.Namespace(arch=None, compose=False) - rc = prepare.run(args) - self.assertEqual(rc, 1) - - @patch("dbuild.prepare.configure_networking") - @patch("dbuild.prepare.cleanup_containers") - @patch("dbuild.prepare.install_ocijail") - @patch("dbuild.prepare.install_packages") - @patch("dbuild.prepare.configure_pkg_repo") - @patch("dbuild.prepare.ci_mod.detect") - @patch("os.geteuid", return_value=0) - def test_full_pipeline_in_ci(self, _euid, mock_ci, mock_pkg, - mock_install, mock_ocijail, - mock_cleanup, mock_net): - """In CI, no confirmation prompt — runs straight through.""" - mock_ci.return_value = MagicMock() # not LocalCI - args = argparse.Namespace(arch=None, compose=False) - rc = prepare.run(args) - self.assertEqual(rc, 0) - mock_pkg.assert_called_once() - mock_install.assert_called_once_with(compose=False) - mock_ocijail.assert_called_once_with(arch=None) - mock_cleanup.assert_called_once() - mock_net.assert_called_once() - - @patch("dbuild.prepare.configure_networking") - @patch("dbuild.prepare.cleanup_containers") - @patch("dbuild.prepare.install_ocijail") - @patch("dbuild.prepare.install_packages") - @patch("dbuild.prepare.configure_pkg_repo", - side_effect=subprocess.CalledProcessError(1, "pkg")) - @patch("dbuild.prepare.ci_mod.detect") - @patch("os.geteuid", return_value=0) - def test_command_failure(self, _euid, mock_ci, mock_pkg, - mock_install, mock_ocijail, - mock_cleanup, mock_net): - mock_ci.return_value = MagicMock() # not LocalCI - args = argparse.Namespace(arch=None, compose=False) - rc = prepare.run(args) - self.assertEqual(rc, 1) - - # The bare-metal tests must not depend on where they run: force detect() - # to LocalCI, or a real CI environment (GITHUB_ACTIONS set) skips the - # confirmation prompt and run() executes the real pipeline. - @patch("dbuild.prepare.ci_mod.detect", return_value=LocalCI()) - @patch("builtins.input", return_value="y") - @patch("dbuild.prepare.configure_networking") - @patch("dbuild.prepare.cleanup_containers") - @patch("dbuild.prepare.install_ocijail") - @patch("dbuild.prepare.install_packages") - @patch("dbuild.prepare.configure_pkg_repo") - @patch("os.geteuid", return_value=0) - def test_bare_metal_confirm_yes(self, _euid, mock_pkg, mock_install, - mock_ocijail, mock_cleanup, mock_net, - _mock_input, _mock_detect): - """On bare metal, answering 'y' proceeds normally.""" - args = argparse.Namespace(arch=None, compose=False) - rc = prepare.run(args) - self.assertEqual(rc, 0) - mock_pkg.assert_called_once() - - @patch("dbuild.prepare.ci_mod.detect", return_value=LocalCI()) - @patch("builtins.input", return_value="n") - @patch("os.geteuid", return_value=0) - def test_bare_metal_confirm_no(self, _euid, _mock_input, _mock_detect): - """On bare metal, answering 'n' aborts.""" - args = argparse.Namespace(arch=None, compose=False) - rc = prepare.run(args) - self.assertEqual(rc, 1) - - @patch("dbuild.prepare.ci_mod.detect", return_value=LocalCI()) - @patch("builtins.input", side_effect=KeyboardInterrupt) - @patch("os.geteuid", return_value=0) - def test_bare_metal_ctrl_c(self, _euid, _mock_input, _mock_detect): - """On bare metal, Ctrl-C aborts.""" - args = argparse.Namespace(arch=None, compose=False) - rc = prepare.run(args) - self.assertEqual(rc, 1) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_registry.py b/tests/test_registry.py index 07744d2..e744105 100644 --- a/tests/test_registry.py +++ b/tests/test_registry.py @@ -60,6 +60,11 @@ def test_url_stored(self): self.assertEqual(reg.url, "ghcr.io/daemonless") self.assertEqual(reg.token, "tok") + def test_dockerhub_no_update_description(self): + self.assertTrue(hasattr(DockerHub, "login")) + self.assertTrue(hasattr(DockerHub, "mirror_from")) + self.assertFalse(hasattr(DockerHub, "update_description")) + if __name__ == "__main__": unittest.main()