Compare commits

...

4 Commits

Author SHA1 Message Date
didericis-codex 97492ffacb ci: enforce pylint score instead of warning exit bits
lint / lint (push) Successful in 2m16s
test / unit (pull_request) Successful in 1m10s
test / integration (pull_request) Successful in 29s
test / coverage (pull_request) Successful in 1m22s
2026-07-18 02:35:18 +00:00
didericis-codex 9d66d1bc49 ci: enforce canonical issue metadata policy
lint / lint (push) Successful in 2m17s
test / unit (pull_request) Successful in 1m8s
test / integration (pull_request) Successful in 26s
test / coverage (pull_request) Successful in 1m19s
2026-07-17 22:34:12 -04:00
didericis 2aec30e501 fix(git-gate): install the gitleaks binary for the build's target arch
The gateway Dockerfile hardcoded the linux_x64 gitleaks download, so an
image built on/for aarch64 (Apple Silicon) baked in an x86_64 binary.
It sat quiet until the git-gate pre-receive hook first invoked it, where
the kernel refused the foreign-arch exec — `gitleaks: Exec format error`
— failing every push through that gateway.

Pick the asset + pinned SHA from the build's target architecture:
TARGETARCH (auto-populated by BuildKit) with a `dpkg --print-architecture`
fallback for a legacy builder, and hard-fail on any unsupported arch.
Each arch keeps its own SHA256 verification, so no supply-chain regression.

The existing integration test test_gateway_image.py::
test_gitleaks_binary_present_and_versioned execs `gitleaks version` in the
built image, so it now passes on arm64 instead of hitting the same error.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 22:14:47 -04:00
didericis b1850be5d1 fix(git-gate): make the gateway access-hook executable regardless of copy transport
test / unit (pull_request) Successful in 1m19s
test / integration (pull_request) Successful in 30s
test / coverage (pull_request) Successful in 1m35s
lint / lint (push) Successful in 2m35s
test / unit (push) Successful in 1m21s
test / integration (push) Successful in 29s
test / coverage (push) Successful in 1m31s
Update Quality Badges / update-badges (push) Successful in 1m21s
Cloning/fetching from the git-gate on the Apple-container backend failed with
"empty reply from server" (curl exit 52). Root cause: the git-http handler
crashed on every upload-pack with

    PermissionError: [Errno 13] Permission denied: '/etc/git-gate/access-hook'

The access-hook is exec'd directly, so it needs the x bit. prepare() stages it
0o700 and trusted the gateway copy to carry that mode. `docker cp` does; the
Apple `container cp` (AppleGatewayTransport) does not, landing the hook 0o644 →
EACCES. The unhandled exception killed the handler thread, closing the socket
with no HTTP response — which the client sees as the opaque empty reply.

- provision_git_gate now `chmod +x`es the access-hook on the gateway side after
  the copy, so it's executable under every transport (docker/apple/firecracker).
- git-http handler wraps the access-hook subprocess.run: an OSError /
  SubprocessError (un-execable, timed out) now fails closed with a 503 instead
  of crashing the thread into an empty reply — a gate that can't run its hook
  should deny, visibly.
- Updates the now-misleading "docker cp preserves source mode" comment in
  git_gate.prepare().

Regression tests: provisioning applies +x to the access-hook; the handler
returns 503 (not an empty reply) when the hook can't be exec'd.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 21:49:30 -04:00
12 changed files with 408 additions and 13 deletions
+13 -2
View File
@@ -25,8 +25,19 @@ jobs:
- name: Run pylint
run: |
# Run pylint on all Python files in the repo
find . -name '*.py' -not -path './.venv/*' -not -path './.git/*' | xargs pylint --fail-under=8.0
# Pylint's normal exit code is nonzero for any emitted finding,
# regardless of --fail-under. Preserve the full report but enforce
# the aggregate score this workflow promises.
set +e
find . -name '*.py' -not -path './.venv/*' -not -path './.git/*' \
| xargs pylint --fail-under=8.0 \
| tee /tmp/pylint-output.txt
set -e
SCORE=$(sed -n \
's/^Your code has been rated at \([-0-9.]*\)\/10.*/\1/p' \
/tmp/pylint-output.txt | tail -1)
test -n "$SCORE"
awk -v score="$SCORE" 'BEGIN { exit !(score >= 8.0) }'
- name: Run pyright
run: |
+33
View File
@@ -0,0 +1,33 @@
name: tracker-policy
on:
issues:
types: [opened, unlabeled]
pull_request:
types: [opened, edited, reopened, synchronized, labeled, unlabeled]
jobs:
label-issue:
if: ${{ github.event_name == 'issues' }}
runs-on: ubuntu-latest
permissions:
issues: write
steps:
- uses: actions/checkout@v4
- name: Ensure the issue has a label
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: python3 scripts/tracker_policy.py label-issue
check-pr:
if: ${{ github.event_name == 'pull_request' }}
runs-on: ubuntu-latest
permissions:
issues: read
pull-requests: read
steps:
- uses: actions/checkout@v4
- name: Require an unlabeled PR linked to an issue
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: python3 scripts/tracker_policy.py check-pr
+17 -3
View File
@@ -66,11 +66,25 @@ RUN pip install --no-cache-dir mitmproxy==11.1.3
# would pin us to that image's cadence). python (already present) does the
# download so we add no curl/wget. trixie apt also ships gitleaks, but an
# older 8.16; the pinned download keeps the verified 8.30.1.
#
# Arch-aware: the asset + SHA are picked from the build's target
# architecture so an arm64 host (Apple Silicon) gets the arm64 binary
# rather than an x86_64 one that dies with "Exec format error" the first
# time the pre-receive hook runs it. TARGETARCH is auto-populated by
# BuildKit; the dpkg fallback keeps it correct under a legacy builder.
ARG GITLEAKS_VERSION=8.30.1
ARG GITLEAKS_SHA256=551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb
RUN url="https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}/gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz" \
ARG GITLEAKS_SHA256_AMD64=551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb
ARG GITLEAKS_SHA256_ARM64=e4a487ee7ccd7d3a7f7ec08657610aa3606637dab924210b3aee62570fb4b080
ARG TARGETARCH
RUN arch="${TARGETARCH:-$(dpkg --print-architecture)}" \
&& case "$arch" in \
amd64) asset="linux_x64"; sha="${GITLEAKS_SHA256_AMD64}" ;; \
arm64) asset="linux_arm64"; sha="${GITLEAKS_SHA256_ARM64}" ;; \
*) echo "unsupported gitleaks target arch: $arch" >&2; exit 1 ;; \
esac \
&& url="https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}/gitleaks_${GITLEAKS_VERSION}_${asset}.tar.gz" \
&& python3 -c "import sys,urllib.request; urllib.request.urlretrieve(sys.argv[1], '/tmp/gitleaks.tar.gz')" "$url" \
&& echo "${GITLEAKS_SHA256} /tmp/gitleaks.tar.gz" | sha256sum -c - \
&& echo "${sha} /tmp/gitleaks.tar.gz" | sha256sum -c - \
&& tar -xzf /tmp/gitleaks.tar.gz -C /usr/bin gitleaks \
&& rm /tmp/gitleaks.tar.gz
+9
View File
@@ -171,6 +171,15 @@ When an outbound DLP detector matches a token, the route's `dlp.outbound_on_matc
More examples in `examples/`. Full design lives under `docs/prds/`; the trust-boundary rationale is in `docs/prds/0011-per-file-md-manifest.md`.
## Tracker policy
Issues are the canonical work items and own all tracker labels; every issue
must have at least one. Pull requests stay unlabeled and deliberately reference
an issue with `Closes #…`, `Part of #…`, or another form defined in
[`ADR 0005`](docs/decisions/0005-issues-own-tracker-metadata.md). Gitea Actions
enforces the convention for new work from 2026-07-18 onward. Earlier closed
PRs are grandfathered rather than given artificial retrospective issues.
## Trademarks
bot-bottle is an independent project and is not affiliated with, endorsed by, or sponsored by Anthropic, PBC. "Claude" and "Claude Code" are trademarks of Anthropic, PBC; the project name uses "claude" descriptively to indicate that the tool runs Claude Code inside a sandbox.
@@ -94,6 +94,12 @@ def provision_git_gate(
transport.exec(["mkdir", "-p", "/etc/git-gate"])
transport.cp_into(str(plan.hook_script), "/etc/git-gate/pre-receive")
transport.cp_into(str(plan.access_hook_script), "/etc/git-gate/access-hook")
# The access-hook is exec'd directly (not via `sh`), so it needs the x bit.
# Set it here rather than trusting the copy to carry the staged 0o700:
# `docker cp` preserves source mode, but the Apple `container cp` does not,
# landing the hook 0o644 → EACCES when the git-http handler tries to exec it.
# chmod on the gateway side is backend-neutral and fixes every transport.
transport.exec(["chmod", "+x", "/etc/git-gate/access-hook"])
creds = _creds_dir(bottle_id)
transport.exec(["mkdir", "-p", creds])
for u in plan.upstreams:
+4 -2
View File
@@ -112,8 +112,10 @@ class GitGate(ABC):
access_hook = stage_dir / "git_gate_access_hook.sh"
access_hook.write_text(git_gate_render_access_hook())
# 0o700 (not 0o600): git daemon execs --access-hook directly,
# not via `sh`, so the script needs the x bit. docker cp
# preserves source mode into the container.
# not via `sh`, so the script needs the x bit. The gateway copy
# does not necessarily preserve this mode (`docker cp` does, the
# Apple `container cp` does not), so provision_git_gate re-applies
# +x on the gateway side — see backend/docker/gateway_provision.py.
access_hook.chmod(0o700)
upstreams_with_files: list[GitGateUpstream] = []
for u in upstreams:
+18 -6
View File
@@ -148,12 +148,24 @@ class GitHttpHandler(BaseHTTPRequestHandler):
"GIT_GATE_ACCESS_HOOK", "/etc/git-gate/access-hook",
)
peer = self.client_address[0]
hook = subprocess.run(
[hook_path, "upload-pack", str(repo_dir), peer, peer],
capture_output=True,
check=False,
timeout=GIT_GATE_TIMEOUT_SECS,
)
try:
hook = subprocess.run(
[hook_path, "upload-pack", str(repo_dir), peer, peer],
capture_output=True,
check=False,
timeout=GIT_GATE_TIMEOUT_SECS,
)
except (OSError, subprocess.SubprocessError) as exc:
# The access-hook couldn't be run (missing, not executable,
# timed out, …). Fail closed with a real HTTP error rather
# than letting the exception kill the handler thread — an
# unhandled exception closes the socket with no response, which
# the client sees as an opaque "empty reply from server".
self.log_message(
"access-hook could not run for %s: %s", parsed.path, exc,
)
self.send_error(503, "git-gate access-hook unavailable")
return
if hook.returncode != 0:
detail = (hook.stderr or hook.stdout).decode(
"utf-8", errors="replace",
@@ -0,0 +1,57 @@
# ADR 0005: Keep tracker metadata on issues
- **Status:** Accepted
- **Date:** 2026-07-18
- **Deciders:** didericis
## Context
Gitea exposes labels on both issues and pull requests. Applying the same labels
to both copies planning metadata, creates a synchronization obligation, and
makes disagreements between the two records possible. At the same time,
unlabelled objects look accidental unless the repository states which object
owns the metadata.
The repository already uses issues as work items and PRs as implementations of
those work items. At this decision's cutoff, all open PRs reference issues, but
121 of 219 historically merged PRs do not. Manufacturing retrospective issues
for that history would create records that never participated in planning and
would make the issue history less truthful.
## Decision
Issues are the canonical tracker records and own labels. Every issue has at
least one label. An issue opened or left without labels receives
`Status/Needs Triage` automatically until it is classified.
Pull requests carry no labels. Every new PR deliberately references at least
one existing issue in its title or description with one of these forms:
- `Closes #123`, `Fixes #123`, or `Resolves #123` when merging completes it.
- `Part of #123`, `Related to #123`, `Refs #123`, or `References #123` when it
contributes without completing it.
Gitea Actions enforces both PR rules as a status check and repairs the empty
issue-label state. Branch protection makes the PR policy check required.
The policy applies from 2026-07-18 onward. Existing issues may be labelled as
they are encountered, but closed PRs are grandfathered: no retrospective
issues or PR labels are created solely to make history conform.
## Consequences
- Classification, priority, and workflow metadata have one source of truth.
- A PR's issue link is the navigation path to its planning metadata.
- Multi-PR issues do not require copied or synchronized labels.
- `Status/Needs Triage` is an intentional fallback, not a final
classification.
- Direct issue creation remains convenient; automation repairs a missing label
immediately after creation because Gitea has no native required-label rule.
- The required check must be configured in branch protection after this
workflow lands.
## Links
- Issue #405.
- `.gitea/workflows/tracker-policy.yml`.
- `scripts/tracker_policy.py`.
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""Enforce the repository's issue/PR metadata policy in Gitea Actions."""
from __future__ import annotations
import argparse
import json
import os
import re
import urllib.error
import urllib.request
from pathlib import Path
from typing import Any
ISSUE_REFERENCE = re.compile(
r"(?im)\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?|part\s+of|"
r"related\s+to|refs?|references)\s+#(\d+)\b"
)
TRIAGE_LABEL = "Status/Needs Triage"
def deliberate_issue_numbers(title: str, body: str) -> set[int]:
"""Return same-repository issue numbers referenced intentionally."""
return {int(match) for match in ISSUE_REFERENCE.findall(f"{title}\n{body}")}
class GiteaApi:
"""Small API client using the Actions-provided repository token."""
def __init__(self, api_url: str, repository: str, token: str) -> None:
self.base = f"{api_url.rstrip('/')}/repos/{repository}"
self.token = token
def request(self, method: str, path: str, payload: object | None = None) -> Any:
data = None if payload is None else json.dumps(payload).encode()
request = urllib.request.Request(
f"{self.base}{path}",
data=data,
method=method,
headers={
"Authorization": f"token {self.token}",
"Content-Type": "application/json",
},
)
with urllib.request.urlopen(request, timeout=15) as response:
if response.status == 204:
return None
return json.load(response)
def check_pull_request(event: dict[str, Any], api: GiteaApi) -> list[str]:
"""Return policy violations for a pull_request event."""
pull = event["pull_request"]
errors: list[str] = []
labels = pull.get("labels") or []
if labels:
errors.append(
"PRs must be unlabeled; put tracker metadata on the linked issue "
f"(found: {', '.join(label['name'] for label in labels)})."
)
numbers = deliberate_issue_numbers(pull.get("title", ""), pull.get("body", ""))
if not numbers:
errors.append(
"PR must reference an issue with Closes/Fixes/Resolves #N, "
"Part of #N, Related to #N, Refs #N, or References #N."
)
return errors
real_issues = 0
for number in sorted(numbers):
try:
item = api.request("GET", f"/issues/{number}")
except urllib.error.HTTPError as error:
if error.code == 404:
errors.append(f"Referenced issue #{number} does not exist.")
continue
raise
if item.get("pull_request") is not None:
errors.append(f"#{number} is a pull request, not an issue.")
else:
real_issues += 1
if not real_issues and not errors:
errors.append("PR must reference at least one real issue.")
return errors
def ensure_issue_label(event: dict[str, Any], api: GiteaApi) -> bool:
"""Apply the triage label if an issue event leaves the issue unlabeled."""
issue = event["issue"]
if issue.get("pull_request") is not None or issue.get("labels"):
return False
labels = api.request("GET", "/labels?limit=100")
triage = next((label for label in labels if label["name"] == TRIAGE_LABEL), None)
if triage is None:
raise RuntimeError(f"repository label {TRIAGE_LABEL!r} does not exist")
api.request("POST", f"/issues/{issue['number']}/labels", {"labels": [triage["id"]]})
return True
def _load_event(path: str) -> dict[str, Any]:
return json.loads(Path(path).read_text(encoding="utf-8"))
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("command", choices=("check-pr", "label-issue"))
parser.add_argument("--event", default=os.environ.get("GITHUB_EVENT_PATH"))
args = parser.parse_args()
if not args.event:
parser.error("--event or GITHUB_EVENT_PATH is required")
api = GiteaApi(
os.environ["GITHUB_API_URL"],
os.environ["GITHUB_REPOSITORY"],
os.environ["GITHUB_TOKEN"],
)
event = _load_event(args.event)
if args.command == "check-pr":
errors = check_pull_request(event, api)
if errors:
print("\n".join(f"::error::{error}" for error in errors))
return 1
print("PR tracker policy passed.")
return 0
changed = ensure_issue_label(event, api)
print(f"Applied {TRIAGE_LABEL}." if changed else "Issue already has a label.")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+12
View File
@@ -69,6 +69,18 @@ class TestProvisionGitGate(unittest.TestCase):
self.assertEqual(1, len(exec_scripts))
self.assertIn("repo=/git/bottle1/${name}.git", exec_scripts[0][-1])
def test_makes_access_hook_executable_on_the_gateway(self) -> None:
# Regression: the access-hook is exec'd directly, so it needs the x
# bit. The copy alone can't be trusted to carry the staged 0o700
# (`docker cp` preserves mode, the Apple `container cp` does not),
# so provisioning must re-apply +x on the gateway side.
calls: list[list[str]] = []
with patch(_RUN, side_effect=_recorder(calls)):
provision_git_gate(DockerGatewayTransport("gw"), "bottle1", _plan(_up("foo")))
self.assertIn(
["docker", "exec", "gw", "chmod", "+x", "/etc/git-gate/access-hook"], calls,
)
def test_omits_known_hosts_copy_when_absent(self) -> None:
calls: list[list[str]] = []
with patch(_RUN, side_effect=_recorder(calls)):
+42
View File
@@ -364,6 +364,48 @@ class TestGitHttpBackend(unittest.TestCase):
self.assertIn("access-hook denied", logged)
self.assertIn("exit=2", logged)
def test_access_hook_that_cannot_run_fails_closed_503(self):
"""Regression: when the access-hook can't be exec'd (missing / not
executable a PermissionError from subprocess.run), the handler must
fail closed with a real HTTP status instead of letting the exception
kill the thread, which closes the socket with no response and the
client sees an opaque "empty reply from server"."""
from http.server import ThreadingHTTPServer
import io
import sys
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "repo.git").mkdir()
old_root = os.environ.get("GIT_PROJECT_ROOT")
os.environ["GIT_PROJECT_ROOT"] = str(root)
self.addCleanup(self._restore_env, old_root)
server = ThreadingHTTPServer(("127.0.0.1", 0), GitHttpHandler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
self.addCleanup(server.shutdown)
self.addCleanup(server.server_close)
with mock.patch(
"bot_bottle.git_http_backend.subprocess.run",
side_effect=PermissionError(13, "Permission denied"),
):
buf = io.StringIO()
with mock.patch.object(sys, "stdout", buf):
req = urllib.request.Request(
f"http://127.0.0.1:{server.server_port}"
"/repo.git/info/refs?service=git-upload-pack",
method="GET",
)
try:
urllib.request.urlopen(req, timeout=5)
self.fail("expected HTTPError 503")
except urllib.error.HTTPError as e: # type: ignore
self.assertEqual(503, e.code)
self.assertIn("access-hook could not run", buf.getvalue())
@staticmethod
def _restore_env(value: str | None) -> None:
if value is None:
+62
View File
@@ -0,0 +1,62 @@
import unittest
from unittest.mock import Mock
from scripts.tracker_policy import (
TRIAGE_LABEL,
check_pull_request,
deliberate_issue_numbers,
ensure_issue_label,
)
class TestDeliberateIssueNumbers(unittest.TestCase):
def test_accepts_completing_and_noncompleting_forms(self):
self.assertEqual(
deliberate_issue_numbers("Fixes #12", "Part of #14; refs #15"),
{12, 14, 15},
)
def test_does_not_treat_incidental_number_as_link(self):
self.assertEqual(deliberate_issue_numbers("Audit #12", "See PR #14"), set())
class TestCheckPullRequest(unittest.TestCase):
def test_accepts_unlabelled_pr_linked_to_real_issue(self):
api = Mock()
api.request.return_value = {"number": 12, "pull_request": None}
event = {"pull_request": {"title": "Change", "body": "Part of #12", "labels": []}}
self.assertEqual(check_pull_request(event, api), [])
def test_rejects_labels_and_pr_reference(self):
api = Mock()
api.request.return_value = {"number": 12, "pull_request": {}}
event = {
"pull_request": {
"title": "Change",
"body": "Closes #12",
"labels": [{"name": "Kind/Bug"}],
}
}
errors = check_pull_request(event, api)
self.assertEqual(len(errors), 2)
self.assertIn("unlabeled", errors[0])
self.assertIn("not an issue", errors[1])
class TestEnsureIssueLabel(unittest.TestCase):
def test_adds_triage_label_to_unlabelled_issue(self):
api = Mock()
api.request.side_effect = [[{"id": 55, "name": TRIAGE_LABEL}], None]
event = {"issue": {"number": 405, "labels": [], "pull_request": None}}
self.assertTrue(ensure_issue_label(event, api))
api.request.assert_any_call("POST", "/issues/405/labels", {"labels": [55]})
def test_leaves_labelled_issue_unchanged(self):
api = Mock()
event = {"issue": {"number": 405, "labels": [{"name": "Kind/Documentation"}]}}
self.assertFalse(ensure_issue_label(event, api))
api.request.assert_not_called()
if __name__ == "__main__":
unittest.main()