Files
Fil-A-Management/tests/test_container.py
T

364 lines
18 KiB
Python

"""Opt-in real stock-image acceptance. Never build or remove an application image."""
import os
import shutil
import subprocess
import tempfile
import textwrap
import time
import unittest
import uuid
from pathlib import Path
from .support import ROOT, clean_environment, git_fixture
class BootstrapDirectoryGuardTests(unittest.TestCase):
def test_runtime_and_data_cannot_own_the_persistent_app_directory(self):
with tempfile.TemporaryDirectory(prefix="fam-directory-guard-") as directory:
directory = Path(directory)
app = directory / "persistent-app"
app.mkdir()
script = app / "start.sh"
shutil.copy2(ROOT / "start.sh", script)
original_script = script.read_bytes()
env = clean_environment() | {
"PUID": str(os.getuid() or 99),
"PGID": str(os.getgid() or 100),
"GIT_REPO_URL": "https://example.invalid/repository.git",
"FAM_RUNTIME_DIR": str(app / "runtime"),
"FAM_DATA_DIR": str(directory / "data"),
}
for field in ("FAM_RUNTIME_DIR", "FAM_DATA_DIR"):
for path in (app, directory):
with self.subTest(field=field, path=path):
result = subprocess.run(
["sh", str(script)],
env=env | {field: str(path)},
capture_output=True,
text=True,
timeout=15,
)
self.assertNotEqual(result.returncode, 0)
self.assertIn("persistente App-Verzeichnis nicht enthalten", result.stderr)
self.assertEqual(script.read_bytes(), original_script)
self.assertFalse((app / "runtime").exists())
self.assertFalse((directory / "data").exists())
@unittest.skipUnless(
os.environ.get("FAM_TEST_DOCKER") == "1",
"Real Docker check: set FAM_TEST_DOCKER=1 on an authorized development Docker host",
)
class ContainerPersistenceTests(unittest.TestCase):
def test_stock_container_restart_and_revision_recreation_preserve_appdata(self):
name = "fam-mvp-test-" + uuid.uuid4().hex[:12]
volume = name + "-data"
image = os.environ.get("FAM_TEST_IMAGE", "python:3.12-alpine")
def docker(*args, timeout=120):
result = subprocess.run(
["docker", *args], cwd=ROOT, text=True, capture_output=True, timeout=timeout
)
if result.returncode:
self.fail(result.stdout + result.stderr)
return result.stdout.strip()
docker("info", "--format", "{{.ServerVersion}}")
with tempfile.TemporaryDirectory(prefix="fam-container-") as directory:
directory = Path(directory)
app = directory / "persistent-app"
app.mkdir()
shutil.copy2(ROOT / "start.sh", app / "start.sh")
original_script = (app / "start.sh").read_bytes()
secrets = directory / "secrets"
secrets.mkdir()
for filename in ("gitea_token", "gitea_ssh_key", "gitea_known_hosts"):
source = secrets / filename
source.write_text("synthetic-" + filename + "\n")
source.chmod(0o600)
repo, first, second = git_fixture(directory)
bundle = directory / "repository.bundle"
subprocess.run(
["git", "bundle", "create", str(bundle), "--all"],
cwd=repo,
check=True,
capture_output=True,
)
docker("pull", image, timeout=300)
try:
docker("volume", "create", volume)
def start(revision):
docker(
"run",
"--detach",
"--init",
"--user",
"0:0",
"--name",
name,
"--security-opt",
"no-new-privileges:true",
"--env",
"PUID=99",
"--env",
"PGID=100",
"--env",
"FAM_RUNTIME_DIR=/app/runtime",
"--env",
"FAM_DATA_DIR=/data",
"--env",
"GIT_REPO_URL=file:///fixtures/repository.bundle",
"--env",
"FAM_ALLOW_LOCAL_GIT=1",
"--env",
"GIT_REVISION=" + revision,
"--env",
"SEED_CATALOG=1",
"--env",
"DJANGO_COOKIE_SECURE=0",
"--mount",
"type=volume,source=" + volume + ",target=/data",
"--mount",
"type=bind,source=" + str(app) + ",target=/app",
"--mount",
"type=bind,source="
+ str(bundle)
+ ",target=/fixtures/repository.bundle,readonly",
"--mount",
"type=bind,source=" + str(secrets) + ",target=/run/secrets,readonly",
image,
"/bin/sh",
"/app/start.sh",
)
def ready():
for _ in range(150):
state = docker("inspect", "--format", "{{.State.Status}}", name)
if state == "exited":
break
probe = subprocess.run(
[
"docker",
"exec",
name,
"python3",
"-c",
"import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/healthz/',timeout=2).read()",
],
capture_output=True,
timeout=10,
)
if probe.returncode == 0:
return
time.sleep(2)
self.fail("Synthetic stock container not ready: " + docker("logs", name))
def manage(code):
return docker(
"exec",
"--user",
"99:100",
name,
"/app/runtime/venv/bin/python",
"/app/runtime/app/manage.py",
"shell",
"-c",
code,
)
def assert_bootstrap_is_protected():
result = docker(
"exec",
"--user",
"99:100",
name,
"python3",
"-c",
textwrap.dedent("""\
import os
import stat
from pathlib import Path
assert os.getuid() == os.geteuid() == 99
assert os.getgid() == os.getegid() == 100
app = Path('/app')
script = app / 'start.sh'
original = script.read_bytes()
replacement = app / 'runtime/replacement-start.sh'
replacement.write_bytes(original)
try:
for operation, attempt in (
('overwrite', lambda: script.write_bytes(original)),
('unlink', script.unlink),
('replace', lambda: replacement.replace(script)),
):
try:
attempt()
except PermissionError:
pass
else:
raise AssertionError(operation + ' of /app/start.sh was allowed')
finally:
replacement.unlink(missing_ok=True)
for path, mode in ((app, 0o755), (script, 0o644)):
info = path.stat()
assert (info.st_uid, info.st_gid) == (0, 0), path
assert stat.S_IMODE(info.st_mode) == mode, path
assert not os.access(path, os.W_OK), path
for path in (app / 'runtime', Path('/data')):
info = path.stat()
assert (info.st_uid, info.st_gid) == (99, 100), path
assert stat.S_IMODE(Path('/data').stat().st_mode) == 0o700
credentials = Path('/run/fil-a-management')
info = credentials.stat()
assert (info.st_uid, info.st_gid) == (0, 0)
assert stat.S_IMODE(info.st_mode) == 0o711
assert not os.access(credentials, os.W_OK)
try:
(credentials / 'attacker-link').symlink_to(app)
except PermissionError:
pass
else:
raise AssertionError('UID99 could plant a credential symlink')
for filename, source in (
('token', 'gitea_token'),
('ssh-key', 'gitea_ssh_key'),
('known-hosts', 'gitea_known_hosts'),
):
path = credentials / filename
info = path.lstat()
assert stat.S_ISREG(info.st_mode), path
assert info.st_nlink == 1, path
assert (info.st_uid, info.st_gid) == (99, 100), path
assert stat.S_IMODE(info.st_mode) == 0o600, path
# The host test runner may be root: its mounted 0600
# originals must not need to be readable as UID99.
assert path.read_bytes() == ('synthetic-' + source + '\\n').encode()
secret = Path('/data/secret.key')
assert stat.S_IMODE(secret.stat().st_mode) == 0o600
assert script.read_bytes() == original
print('BOOTSTRAP_PROTECTED_OK')
"""),
)
self.assertIn("BOOTSTRAP_PROTECTED_OK", result)
start(first)
ready()
assert_bootstrap_is_protected()
manage(
"import secrets; from django.contrib.auth import get_user_model; from django.contrib.sessions.backends.db import SessionStore; from filament.models import Variant,InventoryItem,OrderItem; from filament.services import add_quantity; U=get_user_model(); a=U.objects.create_user('synthetic-one',password=secrets.token_urlsafe(24)); b=U.objects.create_user('synthetic-two',password=secrets.token_urlsafe(24)); v=Variant.objects.first(); add_quantity(InventoryItem,a,v,2); add_quantity(InventoryItem,a,v,1); add_quantity(OrderItem,a,v,2); add_quantity(OrderItem,b,v,1); s=SessionStore(); s['synthetic-marker']='persistent'; s.save()"
)
check = "from django.contrib.sessions.models import Session; from filament.models import InventoryItem,OrderItem; from django.db.models import Sum; assert InventoryItem.objects.get().quantity==3; assert OrderItem.objects.aggregate(n=Sum('quantity'))['n']==3; assert any(s.get_decoded().get('synthetic-marker')=='persistent' for s in Session.objects.all()); print('PERSISTENCE_OK')"
self.assertIn("PERSISTENCE_OK", manage(check))
docker(
"exec",
"--user",
"99:100",
name,
"python3",
"-c",
"from pathlib import Path; Path('/app/runtime/credentials').symlink_to('/app', target_is_directory=True)",
)
# Even privilegedly planted destination links must be unlinked, not followed.
docker(
"exec",
"--user",
"0:0",
name,
"python3",
"-c",
textwrap.dedent("""\
import os
from pathlib import Path
credentials = Path('/run/fil-a-management')
for filename in ('token', 'ssh-key', 'known-hosts'):
(credentials / filename).unlink()
(credentials / 'token').symlink_to('/app/start.sh')
(credentials / 'known-hosts').symlink_to('/app')
target = Path('/run/credential-copy-target')
target.write_text('untouched')
target.chmod(0o644)
os.link(target, credentials / 'ssh-key')
"""),
)
docker("restart", name)
ready()
assert_bootstrap_is_protected()
self.assertEqual(
docker(
"exec", "--user", "99:100", name, "readlink", "/app/runtime/credentials"
),
"/app",
)
docker(
"exec",
"--user",
"0:0",
name,
"python3",
"-c",
"import stat; from pathlib import Path; p=Path('/run/credential-copy-target'); s=p.stat(); assert p.read_text()=='untouched'; assert (s.st_uid,s.st_gid)==(0,0); assert stat.S_IMODE(s.st_mode)==0o644; assert s.st_nlink==1",
)
self.assertIn("PERSISTENCE_OK", manage(check))
docker("rm", "--force", name)
start(second)
ready()
assert_bootstrap_is_protected()
self.assertEqual(
docker(
"exec", "--user", "99:100", name, "readlink", "/app/runtime/credentials"
),
"/app",
)
self.assertIn("PERSISTENCE_OK", manage(check))
self.assertEqual(
docker(
"exec",
"--user",
"99:100",
name,
"git",
"-C",
"/app/runtime/app",
"rev-parse",
"HEAD",
),
second,
)
manage(
"from pathlib import Path; rows=[p for p in Path('/proc').glob('[0-9]*') if any(a.endswith(b'/gunicorn') for a in (p/'cmdline').read_bytes().split(bytes([0])))]; assert rows; assert all(next(l for l in (p/'status').read_text().splitlines() if l.startswith('Uid:')).split()[1:]==['99']*4 for p in rows); assert all(next(l for l in (p/'status').read_text().splitlines() if l.startswith('Gid:')).split()[1:]==['100']*4 for p in rows); print('UNPRIVILEGED_SERVER_OK')"
)
self.assertEqual((app / "start.sh").read_bytes(), original_script)
print(
"REAL Docker: published stock image, root-owned protected /app and start.sh, overwrite/unlink/replace denied for UID/GID 99:100, root-owned /run credentials with symlink planting denied, legacy credential symlink ignored, destination symlinks/hardlinks unlinked, restart, revision recreation, SQLite and session-secret persistence verified."
)
finally:
subprocess.run(["docker", "rm", "--force", name], capture_output=True)
subprocess.run(["docker", "volume", "rm", volume], capture_output=True)
# Return our synthetic bind mount to its caller, even if startup failed after chown.
subprocess.run(
[
"docker",
"run",
"--rm",
"--name",
name + "-cleanup",
"--user",
"0:0",
"--mount",
"type=bind,source=" + str(app) + ",target=/app",
image,
"chown",
f"{os.getuid()}:{os.getgid()}",
"/app",
"/app/start.sh",
],
capture_output=True,
timeout=120,
check=True,
)
# The shared stock image is deliberately NEVER removed.