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
226 changes: 226 additions & 0 deletions controlplane/tests/test_docker_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import os
import time
from pathlib import Path
from typing import Any

import pytest

Expand Down Expand Up @@ -181,3 +182,228 @@ def test_real_old_image_ignores_the_noauth_list(tmp_path: Path) -> None:
assert svc.reload(inst.name)["reloaded"] is True # the blocklist reload still works
finally:
svc.remove(inst.name)


# -- log rotation in the hardened container (cap_drop ALL, read-only, no-new-privileges) --------
# The containers come from the real DockerService, so they carry exactly the control plane's
# security options and the per-instance log volume.

LOGDIR = "/var/log/squid"
LOGROTATE = f"logrotate -f -s {LOGDIR}/.logrotate.state /run/lmnsquid/logrotate.conf"


def _hardened(tmp_path: Path, school: str, port: int, retention: int = 2) -> tuple[Any, Any]:
from lmnsquid.docker_service import DockerService
from lmnsquid.models import Instance

secrets = tmp_path / "secrets"
secrets.mkdir()
(secrets / "it.keytab").write_bytes(b"dummy-keytab-not-valid")
svc = DockerService(secrets_dir=str(secrets), blocklists_dir=str(tmp_path / "lists"))
inst = Instance(
school=school,
role="teachers",
ad_group="teachers",
realm="EXAMPLE.INTERNAL",
visible_hostname=f"squid-{school}.example.internal",
http_port=port,
school_subnets="0.0.0.0/0",
keytab_secret="it.keytab",
cache_size_mb=100,
log_retention_days=retention,
image=IMAGE,
)
svc.remove(inst.name) # clean slate, log volume included
return svc, inst


def _sh(svc: Any, inst: Any, cmd: str) -> tuple[int, bytes]:
"""Run ``cmd`` in the instance container as its root (same capabilities as the entrypoint)."""
code, out = svc._get(inst.name).exec_run(["sh", "-c", cmd])
return int(code), bytes(out)


def _out(svc: Any, inst: Any, cmd: str) -> str:
code, out = _sh(svc, inst, cmd)
assert code == 0, (cmd, out)
return out.decode()


def _request(svc: Any, inst: Any, url: str) -> None:
before = _out(svc, inst, f"cat {LOGDIR}/access.log | wc -l")
_sh(svc, inst, f"squidclient -h 127.0.0.1 -p {inst.http_port} {url}")
deadline = time.monotonic() + 15
while _out(svc, inst, f"cat {LOGDIR}/access.log | wc -l") == before:
assert time.monotonic() < deadline, f"no access-log line for {url}"
time.sleep(0.5)


def _rotate(svc: Any, inst: Any) -> None:
code, out = _sh(svc, inst, LOGROTATE + " 2>&1")
assert code == 0 and b"error" not in out, out.decode()


def _files(svc: Any, inst: Any) -> dict[str, str]:
"""``name -> "<mode> <owner>:<group> <size>"`` of every file in the log directory."""
listing = _out(svc, inst, f"cd {LOGDIR} && stat -c '%n %a %U:%G %s' * .logrotate.state")
return {line.split(" ", 1)[0]: line.split(" ", 1)[1] for line in listing.splitlines()}


def _fill_volume(svc: Any, inst: Any, script: str) -> str:
"""Prepare the instance's log volume before its container exists (an upgraded host)."""
volume = f"lmnsquid-logs-{inst.name}"
svc.client.volumes.create(volume)
out = svc.client.containers.run(
IMAGE,
entrypoint=["sh", "-c", "set -eu; cd " + LOGDIR + "; " + script],
volumes={volume: {"bind": LOGDIR, "mode": "rw"}},
remove=True,
)
return bytes(out).decode()


# The state of a volume that images up to 7.3.9 rotated for a while: every run left an empty 0600
# copy, the next ones renamed it to *.backup, the logs themselves kept growing.
_BACKLOG = (
"seq 1 20000 | awk '{printf \"%d.000 1 10.0.0.1 TCP_DENIED/407 3900 GET "
"http://old-%d.invalid/ - HIER_NONE/- text/html\\n\", 1700000000+$1, $1}' > access.log; "
"echo 'old cache line' > cache.log; "
"for f in access.log.1 access.log.1.gz access.log.1.gz-2026111803.backup "
"access.log.1.gz-2026111903.backup cache.log.1 cache.log.1-2026111803.backup; do "
": > $f; chmod 600 $f; done; "
"echo 'not empty' > access.log.1.gz-2026111703.backup; : > unrelated-empty.txt; "
"chown proxy:proxy *; chmod 640 access.log cache.log; "
# last rotation attempt yesterday, so the entrypoint's first run is due for access.log
"y=$(date -d yesterday +%Y-%-m-%-d); printf 'logrotate state -- version 2\\n"
'"/var/log/squid/access.log" %s-3:0:0\\n"/var/log/squid/cache.log" %s-3:0:0\\n\' '
'"$y" "$y" > .logrotate.state; chmod 640 .logrotate.state; '
)
_LEFTOVERS = [
"access.log.1.gz",
"access.log.1.gz-2026111803.backup",
"access.log.1.gz-2026111903.backup",
"cache.log.1",
"cache.log.1-2026111803.backup",
]


def test_log_rotation_hardened(tmp_path: Path) -> None:
"""copytruncate works under the control plane's capabilities: content in .1, the log
emptied and written on, modes kept, retention honoured (access.log and cache.log)."""
svc, inst = _hardened(tmp_path, "itl", 3196, retention=2)
try:
svc.ensure_running(inst)
for i in range(3):
_request(svc, inst, f"http://before-{i}.invalid/")
access = _out(svc, inst, f"cat {LOGDIR}/access.log")
cache = _out(svc, inst, f"cat {LOGDIR}/cache.log")
assert all(f"before-{i}.invalid" in access for i in range(3)) and cache

_rotate(svc, inst)
files = _files(svc, inst)
# (the image's healthcheck may add a line at any time, hence prefix, not equality)
assert _out(svc, inst, f"cat {LOGDIR}/access.log.1").startswith(access)
assert "before-" not in _out(svc, inst, f"cat {LOGDIR}/access.log")
assert files["access.log"].startswith("640 proxy:proxy ")
assert files["access.log.1"].startswith("640 proxy:proxy ")
assert _out(svc, inst, f"zcat {LOGDIR}/cache.log.1.gz").startswith(cache)
assert files["cache.log.1.gz"].startswith("640 proxy:proxy ")
assert files["cache.log"].startswith("640 proxy:proxy ")

# squid writes on into the truncated log (no hole of NULs), the tailer follows it
_request(svc, inst, "http://after-rotation.invalid/")
code, raw = _sh(svc, inst, f"cat {LOGDIR}/access.log")
assert code == 0 and b"\0" not in raw and b"before-" not in raw
assert b"after-rotation.invalid" in raw
time.sleep(2)
assert "after-rotation.invalid" in svc.logs(inst.name, tail=20)

# retention: rotate 2 (access.log) and rotate 4 (cache.log), the older ones go
for i in range(5):
_request(svc, inst, f"http://day-{i}.invalid/")
_sh(svc, inst, f"echo 'cache line {i}' >> {LOGDIR}/cache.log")
_rotate(svc, inst)
files = _files(svc, inst)
assert sorted(files) == [
".logrotate.state",
"access.log",
"access.log.1",
"access.log.2.gz",
"cache.log",
"cache.log.1.gz",
"cache.log.2.gz",
"cache.log.3.gz",
"cache.log.4.gz",
], files
for name, stat in files.items():
if name != ".logrotate.state":
assert stat.startswith("640 proxy:proxy "), (name, stat)
assert "day-4.invalid" in _out(svc, inst, f"cat {LOGDIR}/access.log.1")
assert "day-3.invalid" in _out(svc, inst, f"zcat {LOGDIR}/access.log.2.gz")
assert "logrotate failed" not in svc.logs(inst.name, tail=200)
finally:
svc.remove(inst.name)


def test_log_rotation_after_upgrade(tmp_path: Path) -> None:
"""A volume from the broken rotation: the empty leftovers go (nothing with content), the
backlog is rotated by the first scheduled run and compressed by the next one."""
svc, inst = _hardened(tmp_path, "itu", 3195, retention=30)
try:
backlog_sha = _fill_volume(svc, inst, _BACKLOG + "sha256sum access.log").split()[0]
svc.ensure_running(inst)
deadline = time.monotonic() + 30
while "access.log.1" not in _files(svc, inst):
assert time.monotonic() < deadline, _files(svc, inst)
time.sleep(1)

files = _files(svc, inst)
for name in _LEFTOVERS:
assert name not in files, (name, files)
assert _out(svc, inst, f"cat {LOGDIR}/access.log.1.gz-2026111703.backup") == "not empty\n"
assert "unrelated-empty.txt" in files
log = svc.logs(inst.name, tail=200)
assert "removed 6 empty file(s) left by failed log rotations" in log
assert "logrotate failed" not in log

# the not forced first run rotated the backlog completely into .1, with the log's mode
assert _out(svc, inst, f"sha256sum < {LOGDIR}/access.log.1").split()[0] == backlog_sha
assert files["access.log.1"].startswith("640 proxy:proxy ")
assert files["access.log"].startswith("640 proxy:proxy ")
assert "old-" not in _out(svc, inst, f"cat {LOGDIR}/access.log")
# cache.log is weekly: not due yet, left alone
assert files["cache.log"].startswith("640 proxy:proxy ") and "cache.log.1" not in files

# the next day the backlog is compressed (delaycompress) and still complete
_request(svc, inst, "http://next-day.invalid/")
_rotate(svc, inst)
sha = _out(svc, inst, f"zcat {LOGDIR}/access.log.2.gz | sha256sum").split()[0]
assert sha == backlog_sha
assert _files(svc, inst)["access.log.2.gz"].startswith("640 proxy:proxy ")
finally:
svc.remove(inst.name)


def test_log_rotation_error_reported(tmp_path: Path) -> None:
"""A failing rotation is no longer silent: one line in the container log per run."""
svc, inst = _hardened(tmp_path, "ite", 3194)
try:
# a rotated file proxy cannot read: compressing it as the log's owner must fail
_fill_volume(
svc,
inst,
_BACKLOG + "rm -f access.log.1; echo secret > access.log.1; chmod 600 access.log.1; "
"chmod 644 .logrotate.state", # a warning first: the error line must still win
)
svc.ensure_running(inst)
deadline = time.monotonic() + 30
while "logrotate failed" not in svc.logs(inst.name, tail=200):
assert time.monotonic() < deadline, svc.logs(inst.name, tail=200)
time.sleep(1)
failed = [ln for ln in svc.logs(inst.name, tail=200).splitlines() if "logrotate" in ln]
assert len(failed) == 1, failed
assert failed[0].startswith(
"linuxmuster-squid: logrotate failed (1 error(s)), first: error:"
)
finally:
svc.remove(inst.name)
19 changes: 19 additions & 0 deletions debian/changelog
Original file line number Diff line number Diff line change
@@ -1,3 +1,22 @@
linuxmuster-squid (7.3.10) lmn73; urgency=medium

* Fix the rotation of the access and cache log, which never worked in the
hardened container: access.log grew without limit, every night left an
empty access.log.1 / access.log.1.gz / *.backup with mode 0600 and the
retention (log_retention_days) deleted nothing. logrotate now rotates
as the log's owner (no new capability). On its first start the fixed
image deletes those empty files (only empty files with logrotate's
names, nothing with content); the grown access.log is rotated in full
on the next calendar day (it needs that much free space for a moment)
and deleted log_retention_days days later, so its oldest lines outlive
the retention unless you trim them (docs/operations.md, "After
upgrading"). A failed rotation now writes one line to the container
log ("logrotate failed"). Takes effect with a data-plane image built
from this release (DEFAULT_IMAGE pinned to it); instances on an older
image keep the old behaviour until "lmnsquid update".

-- Kevin Stenzel <mail@kevin-stenzel.de> Thu, 19 Nov 2026 16:25:06 +0100

linuxmuster-squid (7.3.9) lmn73; urgency=medium

* New per-instance setting for the Kerberos clock skew the proxy accepts,
Expand Down
50 changes: 48 additions & 2 deletions docs/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -410,8 +410,54 @@ logs; all request/cache logs live in the Docker volumes above.
→ `docker/lmnsquid logs` (live view, capped docker-json log); (2) the **durable, searchable
history** lives gzip-rotated in the **persistent log volume** `lmnsquid-logs-<name>`
(`/var/log/squid`), surviving restarts/updates.
- **Rotation:** `logrotate` rotates daily + gzip; retained is `--log-retention-days`
(default **30**, configurable up to 3650) → that *is* the retention/deletion period.
- **Rotation:** `logrotate` in the container (checked hourly, state in the volume,
`/var/log/squid/.logrotate.state`) rotates the access log daily (first run on a new calendar
day, container time = UTC) with `copytruncate` (the content moves to `access.log.1`, the log
is emptied and squid writes on), gzips it a day later (`access.log.2.gz` …) and keeps
`--log-retention-days` rotations (default **30**, configurable up to 3650) → that *is* the
retention/deletion period. `cache.log` is rotated weekly, 4 kept. It rotates as the log's
owner `proxy` (`su proxy proxy`): the container has no `CAP_FOWNER`, and as root logrotate
could not set the mode/ACL of the copy (images up to 7.3.9, see below). A failed run writes
**one** line to the container log: `linuxmuster-squid: logrotate failed (<n> error(s)),
first: <first error>` (`docker logs lmnsquid-<name> 2>&1 | grep logrotate`). Known limit of
`copytruncate`: lines squid writes between the copy and the truncation are lost. The window
grows with the size of the log: for a day's log it is short, but the first rotation of a
large backlog (GB, see below) can lose a few lines.
- **Check the rotation:** `docker exec lmnsquid-<name> ls -la /var/log/squid` — a few days
after the start there are `access.log.1` and `access.log.<n>.gz`, all `proxy proxy` with mode
`-rw-r-----` like `access.log`, none of them empty, `access.log` itself not older than a day;
`docker exec lmnsquid-<name> cat /var/log/squid/.logrotate.state` shows the last run.
- **After upgrading from an image up to 7.3.9 (broken rotation):** those images never rotated
in the hardened container: `access.log` grew without limit, and every night left an empty
`access.log.1` / `access.log.1.gz` / `*.backup` with mode `-rw-------`; the retention did not
apply. The fixed image deletes these **empty** files when the container starts (only empty
files with logrotate's names; it logs `removed <n> empty file(s) left by failed log
rotations`), nothing with content. The backlog is then rotated like any other day: at the
first hourly run on the next calendar day (at once, if the last attempt was on an earlier
day) all of it moves to `access.log.1`, one day later to `access.log.2.gz`, and it is deleted
when it would become rotation `--log-retention-days` + 1, i.e. `--log-retention-days` days
after it became `access.log.1`: about `--log-retention-days` + 1 to 2 days after the upgrade. **Disk:** the copy needs free space of the
size of `access.log` for a moment, the compression a day later the size of the `.gz` on top. **Data
protection (T13):** the backlog's oldest lines (back to when the rotation stopped working)
are kept until then, longer than the retention promises. To keep the deletion period
strict, trim them once the backlog has been rotated, while it is `access.log.1` (replace 30
with the instance's retention):

```bash
docker exec lmnsquid-<name> sh -c 'cd /var/log/squid && c=$(( $(date +%s) - 30*86400 )) &&
awk -v c="$c" "\$1+0 >= c" access.log.1 > trim && chmod 640 trim &&
chown proxy:proxy trim && mv trim access.log.1'
```

or, if it is already `access.log.2.gz`:

```bash
docker exec lmnsquid-<name> sh -c 'cd /var/log/squid && c=$(( $(date +%s) - 30*86400 )) &&
zcat access.log.2.gz | awk -v c="$c" "\$1+0 >= c" | gzip > trim && chmod 640 trim &&
chown proxy:proxy trim && mv trim access.log.2.gz'
```

Both keep every line whose timestamp (first field) is within the retention.
- **Query history:** `GET /v1/instances/{name}/logs/access?since=&until=&grep=` or
`lmnsquid access-logs …` searches all rotated `.gz` daily files.
- **Disk space:** roughly `retention-days × ~2 MB packed × instances` — at 90 days
Expand Down
10 changes: 10 additions & 0 deletions docs/test-strategy.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,16 @@ acceptance list in `deployment-gpo.md`.
rollback after a failed update, rollback, update-all, reconcile; a hand-edited definition is
picked up by reconcile/update, an invalid one skipped; the entrypoint check itself
(`sh image/entrypoint.sh` up to a stubbed `mkdir`).
- **Log rotation (T13):** cp-docker-it (`test_log_rotation_*`, containers from the real
DockerService, so with its `cap_drop ALL` + four caps, read-only rootfs, no-new-privileges and
log volume): forced rotation moves the content completely into `access.log.1`, empties the
log, squid writes on without NULs and the tailer follows; modes `640 proxy:proxy` kept;
after six rotations exactly `access.log.1`, `.2.gz` (retention 2) and `cache.log.1..4.gz`;
a volume as 7.3.9 left it (backlog, empty `.1`/`.1.gz`/`*.backup`, state from yesterday):
the empty leftovers are removed and logged, a non-empty `*.backup` and an unrelated empty
file stay, the first unforced run rotates the backlog byte-identical, the next compresses
it; a rotation that fails logs exactly one `logrotate failed … first: error:` line. All three
are red against the 7.3.9 image (`LMNSQUID_IT_IMAGE=<old image>`).
- **P10:** keytab perms; manager ACL not reachable externally; API bind ≠ 0.0.0.0;
bypass/traversal; DC outage does not stall (ttl/grace).

Expand Down
Loading
Loading