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
85 changes: 85 additions & 0 deletions .github/scripts/update_debian_snapshot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
#!/usr/bin/env python3
"""Advance the agent-server Debian snapshot after a seven-day observation period."""

from __future__ import annotations

import argparse
import re
import urllib.request
from datetime import UTC, datetime, timedelta
from pathlib import Path


MINIMUM_AGE = timedelta(days=7)
SNAPSHOT_RE = re.compile(r"(?m)^ARG DEBIAN_SNAPSHOT=(\d{8}T\d{6}Z)$")
ARCHIVES = ("debian", "debian-security")


def eligible_snapshot(now: datetime) -> datetime:
if now.tzinfo is None:
raise ValueError("now must be timezone-aware")
cutoff = now.astimezone(UTC) - MINIMUM_AGE
return cutoff.replace(hour=0, minute=0, second=0, microsecond=0)


def format_snapshot(value: datetime) -> str:
return value.astimezone(UTC).strftime("%Y%m%dT%H%M%SZ")


def validate_snapshot_age(snapshot: datetime, now: datetime) -> None:
age = now.astimezone(UTC) - snapshot.astimezone(UTC)
if age < MINIMUM_AGE:
raise ValueError(f"snapshot is only {age} old; minimum age is {MINIMUM_AGE}")


def verify_snapshot(snapshot: str) -> None:
for archive in ARCHIVES:
url = f"https://snapshot.debian.org/archive/{archive}/{snapshot}/"
request = urllib.request.Request(url, method="HEAD")
try:
with urllib.request.urlopen(request, timeout=30) as response:
if response.status != 200:
raise ValueError(f"{url} returned HTTP {response.status}")
except OSError as exc:
raise ValueError(f"unable to verify {url}: {exc}") from exc


def update_dockerfile(path: Path, snapshot: str) -> bool:
text = path.read_text(encoding="utf-8")
matches = SNAPSHOT_RE.findall(text)
if len(matches) != 1:
raise ValueError(f"expected exactly one DEBIAN_SNAPSHOT in {path}")
updated = SNAPSHOT_RE.sub(f"ARG DEBIAN_SNAPSHOT={snapshot}", text)
if updated == text:
return False
path.write_text(updated, encoding="utf-8")
return True


def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dockerfile", type=Path, required=True)
parser.add_argument(
"--now",
type=lambda value: datetime.fromisoformat(value.replace("Z", "+00:00")),
default=datetime.now(UTC),
help="UTC reference time for deterministic testing",
)
parser.add_argument("--skip-network-check", action="store_true")
return parser.parse_args()


def main() -> int:
args = parse_args()
snapshot_time = eligible_snapshot(args.now)
validate_snapshot_age(snapshot_time, args.now)
snapshot = format_snapshot(snapshot_time)
if not args.skip_network_check:
verify_snapshot(snapshot)
changed = update_dockerfile(args.dockerfile, snapshot)
print(f"Debian snapshot: {snapshot} ({'updated' if changed else 'unchanged'})")
return 0


if __name__ == "__main__":
raise SystemExit(main())
78 changes: 78 additions & 0 deletions .github/workflows/update-debian-snapshot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
---
name: Update Automation Debian Snapshot

on:
schedule:
- cron: 17 6 * * 1
workflow_dispatch:

permissions:
contents: write
pull-requests: write

concurrency:
group: update-automation-debian-snapshot
cancel-in-progress: true

jobs:
update-snapshot:
runs-on: ubuntu-24.04
timeout-minutes: 30
env:
GH_TOKEN: ${{ secrets.OPENHANDS_BOT_GITHUB_PAT_PUBLIC }}
BRANCH: chore/update-automation-debian-snapshot
DOCKERFILE: containers/Dockerfile
IMAGE: openhands/automation:snapshot-update
steps:
- name: Checkout
uses: actions/checkout@v4
with:
token: ${{ secrets.OPENHANDS_BOT_GITHUB_PAT_PUBLIC }}
- name: Select newest snapshot older than seven days
run: python .github/scripts/update_debian_snapshot.py --dockerfile "$DOCKERFILE"
- name: Build image
run: docker build --tag "$IMAGE" --file "$DOCKERFILE" .
- name: Scan image
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
with:
image-ref: ${{ env.IMAGE }}
format: json
output: trivy.json
scanners: vuln
- name: Open or refresh update PR
env:
REPO: ${{ github.repository }}
run: |
set -euo pipefail
if git diff --quiet; then
echo "Debian snapshot is already current."
exit 0
fi
SNAPSHOT=$(sed -n 's/^ARG DEBIAN_SNAPSHOT=//p' "$DOCKERFILE")
TRIVY_COUNTS=$(jq -r '[.Results[]?.Vulnerabilities[]?] | group_by(.Severity) | map("\(.[0].Severity): \(length)") | join(", ")' trivy.json)
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git fetch origin "$BRANCH" || true
git checkout -B "$BRANCH"
git add "$DOCKERFILE"
git commit -m "chore(automation): update Debian snapshot to $SNAPSHOT" \
-m "Use the newest UTC snapshot that has completed the seven-day observation period." \
-m "Co-authored-by: openhands <openhands@all-hands.dev>"
git push --force-with-lease -u origin "$BRANCH"
BODY=$(cat <<EOF2
## Summary
Advance the automation runtime to Debian snapshot \\`$SNAPSHOT\\`, the newest UTC snapshot that completed the seven-day observation period.

The workflow built and scanned the image before opening this PR.

**Trivy findings:** $TRIVY_COUNTS

_This pull request was created by an automated workflow._
EOF2
)
EXISTING=$(gh pr list --repo "$REPO" --head "$BRANCH" --state open --json number --jq '.[0].number')
if [ -n "$EXISTING" ]; then
gh pr edit "$EXISTING" --repo "$REPO" --title "chore(automation): update Debian snapshot to $SNAPSHOT" --body "$BODY"
else
gh pr create --repo "$REPO" --base main --head "$BRANCH" --title "chore(automation): update Debian snapshot to $SNAPSHOT" --body "$BODY"
fi
22 changes: 20 additions & 2 deletions containers/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
FROM python:3.12-slim-bookworm
FROM python:3.12-slim-trixie

ARG DEBIAN_SNAPSHOT=20260913T000000Z

WORKDIR /app
ENV PYTHONPATH='/app'
Expand All @@ -7,8 +9,24 @@ ENV PYTHONPATH='/app'
LABEL com.datadoghq.tags.service="automation"

# Install system deps for asyncpg + uv + git (for SDK git dependencies)
RUN apt-get update && \
RUN printf '%s\n' \
'Types: deb' \
"URIs: http://snapshot.debian.org/archive/debian/${DEBIAN_SNAPSHOT}/" \
'Suites: trixie' \
'Components: main' \
'Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg' \
'Check-Valid-Until: no' \
'' \
'Types: deb' \
"URIs: http://snapshot.debian.org/archive/debian-security/${DEBIAN_SNAPSHOT}/" \
'Suites: bookworm-security' \
'Components: main' \
'Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg' \
'Check-Valid-Until: no' \
> /etc/apt/sources.list.d/debian.sources && \
apt-get update && \
apt-get install -y --no-install-recommends libpq-dev git && \
apt-get upgrade -y --no-install-recommends && \
apt-get clean && rm -rf /var/lib/apt/lists/* && \
pip install --no-cache-dir uv ddtrace

Expand Down
63 changes: 63 additions & 0 deletions tests/test_update_debian_snapshot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
from datetime import UTC, datetime, timedelta
from importlib.util import module_from_spec, spec_from_file_location
from pathlib import Path

import pytest


REPO_ROOT = Path(__file__).resolve().parents[1]
SCRIPT_PATH = REPO_ROOT / ".github" / "scripts" / "update_debian_snapshot.py"
SPEC = spec_from_file_location("update_debian_snapshot", SCRIPT_PATH)
assert SPEC and SPEC.loader
snapshot = module_from_spec(SPEC)
SPEC.loader.exec_module(snapshot)


def test_eligible_snapshot_is_at_least_seven_days_old() -> None:
now = datetime(2026, 9, 15, 12, 30, tzinfo=UTC)

selected = snapshot.eligible_snapshot(now)

assert selected == datetime(2026, 9, 8, tzinfo=UTC)
assert now - selected >= timedelta(days=7)


def test_validate_snapshot_age_rejects_fresh_snapshot() -> None:
now = datetime(2026, 9, 15, 12, 30, tzinfo=UTC)

with pytest.raises(ValueError, match="minimum age"):
snapshot.validate_snapshot_age(now - timedelta(days=6), now)


def test_update_dockerfile_replaces_exactly_one_pin(tmp_path: Path) -> None:
dockerfile = tmp_path / "Dockerfile"
dockerfile.write_text(
"FROM debian:trixie-slim\nARG DEBIAN_SNAPSHOT=20260901T000000Z\n"
)

assert snapshot.update_dockerfile(dockerfile, "20260908T000000Z")
assert "ARG DEBIAN_SNAPSHOT=20260908T000000Z" in dockerfile.read_text()
assert not snapshot.update_dockerfile(dockerfile, "20260908T000000Z")


def test_update_dockerfile_rejects_missing_pin(tmp_path: Path) -> None:
dockerfile = tmp_path / "Dockerfile"
dockerfile.write_text("FROM debian:trixie-slim\n")

with pytest.raises(ValueError, match="exactly one"):
snapshot.update_dockerfile(dockerfile, "20260908T000000Z")


def test_workflow_builds_and_scans_before_opening_pr() -> None:
workflow = (
REPO_ROOT / ".github" / "workflows" / "update-debian-snapshot.yml"
).read_text()

build = workflow.index("- name: Build image")
scan = workflow.index("- name: Scan image")
pull_request = workflow.index("- name: Open or refresh update PR")
assert build < scan < pull_request
assert (
"aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25" in workflow
)
assert "cron: 17 6 * * 1" in workflow
Loading