feat: the bundled database's application gets its own restricted login (NetOrk/netork#2937)
CI / check (pull_request) Successful in 22s

remote/db_login.sh runs after .env names the version and before the broker
and the engine: a container of the engine image being deployed
(python -m netork.core.db_role_env) rewrites .env so that the owner's URL
becomes MIGRATION_DATABASE_URL and DATABASE_URL a netork_app login with a
password made on the host; netork-api's db_init creates the role. No bundled
database, an image from before the module, an .env separated already or
RESTRICTED_DB_LOGIN=off: .env stays as it is. Any other failure stops the
deploy before the engine is touched.
This commit is contained in:
Christian Manivong committed 2026-12-02 02:35:23 +01:00
1 parent e35d42a20b
commit ec7d113cdb
5 files changed
+305 -7

No files matched your search

+89
View File
@@ -0,0 +1,89 @@
"""deploy.sh runs remote/db_login.sh on every host (NetOrk/netork#2937).
On the bundled database the application gets a login of its own that cannot
change the audit log. The step runs after the database step and after .env names
the new version, and before the broker and the engine, so the recreated
containers start with the new login. A failure stops the deploy there, with the
old engine still running.
The remote side is a fake `ssh` that records every command and what it was fed.
"""
from __future__ import annotations
import os
import subprocess
from pathlib import Path
DEPLOY = Path(__file__).resolve().parent.parent / "deploy.sh"
DB_LOGIN = Path(__file__).resolve().parent.parent / "remote" / "db_login.sh"
_FAKE_SSH = """#!/bin/sh
for arg in "$@"; do cmd="$arg"; done
case "$cmd" in *.deploy.lock*) exec sh -c "$cmd" ;; esac
printf '%s\\n----\\n' "$cmd" >> "{state}/commands"
case "$cmd" in
*"ENGINE_IMAGE="*"bash -s"*) cat > "{state}/db-login-stdin"; exit {login_exit} ;;
esac
cat > /dev/null
exit 0
"""
def _deploy(tmp_path: Path, *, login_exit: int = 0):
bin_dir = tmp_path / "bin"
bin_dir.mkdir()
fake = bin_dir / "ssh"
fake.write_text(
_FAKE_SSH.replace("{state}", str(tmp_path)).replace("{login_exit}", str(login_exit))
)
fake.chmod(0o755)
result = subprocess.run(
["bash", str(DEPLOY), "testhost"],
env={
"PATH": f"{bin_dir}:{os.environ['PATH']}",
"HOME": str(tmp_path),
"DEPLOY_ENV_FILE": "/dev/null",
"REGISTRY_HOST": "registry.example",
"NETORK_VERSION": "latest-dev",
},
stdin=subprocess.DEVNULL,
capture_output=True,
text=True,
timeout=60,
check=False,
)
commands = (tmp_path / "commands").read_text().split("\n----\n")
return result, commands
def _index(commands: list[str], needle: str) -> int:
return next(i for i, c in enumerate(commands) if needle in c)
def test_the_login_step_runs_with_the_deployed_engine_image(tmp_path: Path) -> None:
result, commands = _deploy(tmp_path)
assert result.returncode == 0, result.stdout + result.stderr
(step,) = [c for c in commands if "ENGINE_IMAGE=" in c]
assert step.strip() == "ENGINE_IMAGE='registry.example/netork/engine:latest-dev' bash -s"
assert (tmp_path / "db-login-stdin").read_text() == DB_LOGIN.read_text()
def test_it_runs_after_env_names_the_version_and_before_broker_and_engine(tmp_path: Path) -> None:
_, commands = _deploy(tmp_path)
login = _index(commands, "ENGINE_IMAGE=")
env_write = next(i for i, c in enumerate(commands) if c.strip() == "bash -s")
assert _index(commands, "bash -s -- reconcile") < login
assert env_write < login
assert login < _index(commands, "--wait-timeout 120 redis")
assert login < _index(commands, "--force-recreate")
def test_a_failure_stops_before_the_engine(tmp_path: Path) -> None:
result, commands = _deploy(tmp_path, login_exit=1)
assert result.returncode != 0
assert not any("--force-recreate" in c for c in commands)
assert not any("redis" in c and "up -d" in c for c in commands)
+129
View File
@@ -0,0 +1,129 @@
"""The bundled database's restricted application login (NetOrk/netork#2937): remote/db_login.sh.
deploy.sh runs it on the host after the database step and before the engine is
recreated. The engine image being deployed decides (``python -m
netork.core.db_role_env``, ``.env`` on stdin): exit 0 and the new ``.env`` on
stdout, or exit 3 and nothing to do. The script only writes what it got back,
in place, so the file keeps its owner and mode.
- no bundled database (external PostgreSQL): nothing runs, ``.env`` stays;
- an image without the module (a version before it): ``.env`` stays, the deploy goes on;
- any other failure stops the deploy before the engine is touched, ``.env`` as it was.
The remote side is a fake ``docker`` that records each call.
"""
from __future__ import annotations
import os
import stat
import subprocess
from pathlib import Path
SCRIPT = Path(__file__).resolve().parent.parent / "remote" / "db_login.sh"
ENGINE = "registry.example/netork/engine:0.60.0"
BEFORE = "POSTGRES_PASSWORD=pg\nDATABASE_URL=postgresql+asyncpg://netork:pw@postgres:5432/netork\n"
AFTER = BEFORE + "MIGRATION_DATABASE_URL=owner\n"
_FAKE_DOCKER = r"""#!/bin/bash
printf '%s\n' "$*" >> "$FAKE_STATE/calls"
case "$1" in
ps) [ -n "$FAKE_PG_CID" ] && echo "$FAKE_PG_CID"; exit 0 ;;
run)
cat > "$FAKE_STATE/stdin"
case "$FAKE_MODE" in
changed) printf '%s' "$FAKE_AFTER"; exit 0 ;;
nothing) exit 3 ;;
old) echo "/opt/venv/bin/python: No module named netork.core.db_role_env" >&2; exit 1 ;;
broken) echo "Traceback: boom" >&2; exit 1 ;;
esac ;;
esac
exit 0
"""
def _run(tmp_path: Path, *, mode: str, bundled: bool = True) -> subprocess.CompletedProcess[str]:
home = tmp_path / "home"
(home / "netork").mkdir(parents=True)
env_file = home / "netork" / ".env"
env_file.write_text(BEFORE)
env_file.chmod(0o640)
bin_dir = tmp_path / "bin"
bin_dir.mkdir()
docker = bin_dir / "docker"
docker.write_text(_FAKE_DOCKER)
docker.chmod(0o755)
return subprocess.run(
["bash", "-s"],
stdin=SCRIPT.open(),
capture_output=True,
text=True,
env={
"PATH": f"{bin_dir}:{os.environ['PATH']}",
"HOME": str(home),
"ENGINE_IMAGE": ENGINE,
"FAKE_STATE": str(tmp_path),
"FAKE_MODE": mode,
"FAKE_AFTER": AFTER,
"FAKE_PG_CID": "pgcid" if bundled else "",
},
check=False,
)
def _env(tmp_path: Path) -> Path:
return tmp_path / "home" / "netork" / ".env"
def _leftovers(tmp_path: Path) -> list[str]:
return sorted(p.name for p in (tmp_path / "home" / "netork").iterdir() if p.name != ".env")
def test_the_new_env_from_the_engine_image_is_written_in_place(tmp_path):
result = _run(tmp_path, mode="changed")
assert result.returncode == 0, result.stderr
assert _env(tmp_path).read_text() == AFTER
assert stat.S_IMODE(_env(tmp_path).stat().st_mode) == 0o640
assert (tmp_path / "stdin").read_text() == BEFORE
run = next(c for c in (tmp_path / "calls").read_text().splitlines() if c.startswith("run "))
assert run == (
f"run --rm -i --network none --entrypoint python {ENGINE} -m netork.core.db_role_env"
)
assert "restricted" in result.stdout
assert "owner" not in result.stdout + result.stderr # nothing of the file is echoed
assert _leftovers(tmp_path) == []
def test_nothing_to_do_leaves_the_file(tmp_path):
result = _run(tmp_path, mode="nothing")
assert result.returncode == 0, result.stderr
assert _env(tmp_path).read_text() == BEFORE
assert _leftovers(tmp_path) == []
def test_without_a_bundled_database_the_image_is_not_asked(tmp_path):
result = _run(tmp_path, mode="changed", bundled=False)
assert result.returncode == 0, result.stderr
assert _env(tmp_path).read_text() == BEFORE
assert "run " not in (tmp_path / "calls").read_text()
def test_an_image_without_the_module_leaves_the_file_and_goes_on(tmp_path):
result = _run(tmp_path, mode="old")
assert result.returncode == 0, result.stderr
assert _env(tmp_path).read_text() == BEFORE
assert "cannot" in result.stdout
assert _leftovers(tmp_path) == []
def test_any_other_failure_stops_with_the_file_as_it_was(tmp_path):
result = _run(tmp_path, mode="broken")
assert result.returncode == 1
assert _env(tmp_path).read_text() == BEFORE
assert "boom" in result.stderr
assert _leftovers(tmp_path) == []