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
9 changes: 9 additions & 0 deletions deploy/activate.sh
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,15 @@ if [[ -n "${MUTATING_EXPECTED_CURRENT:-}" && "$(readlink -f "$deploy_root/curren
echo "The active release changed during preparation; inspect it before activating this release." >&2
exit 2
fi
# The enrollment secret only protects the recoverable credential used by an
# exact finish retry. Generate it once on servers upgraded from the ACME flow
# so a code-only deployment cannot leave computer registration at HTTP 503.
if ! grep -Eq '^[[:space:]]*THRONG_ENROLLMENT_SECRET=.+$' "$server_env"; then
enrollment_secret="$(openssl rand -hex 32)"
printf '\nTHRONG_ENROLLMENT_SECRET=%s\n' "$enrollment_secret" >> "$server_env"
chmod 0640 "$server_env"
echo 'Configured a new Power Cell enrollment secret.'
fi
backup_id="$release_id-$(date -u +%Y%m%dT%H%M%S)"
maintenance=(runuser -u throng -- "$release/platform/api/.venv/bin/python")
if ! "${maintenance[@]}" "$backup_script" check-space "$backup_id" --env-file "$server_env"; then
Expand Down
50 changes: 49 additions & 1 deletion deploy/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import argparse
import logging
import os
import secrets
import signal
import subprocess
import sys
Expand All @@ -21,6 +22,49 @@
logger = logging.getLogger("throng.platform")


def ensure_enrollment_secret(settings):
"""Return the configured secret or create a persistent local fallback.

Production already sets THRONG_ENROLLMENT_SECRET in its environment. The
fallback keeps a code-only CI deployment usable and is stored beside the
persistent data so exact finish retries survive service restarts.
"""
if settings.enrollment_secret:
return settings.enrollment_secret
path = settings.storage_path.parent / ".enrollment-secret"
try:
secret = path.read_text(encoding="utf-8").strip()
if len(secret) >= 32:
return secret
raise ValueError("stored enrollment secret is too short")
except FileNotFoundError:
pass
except (OSError, ValueError) as error:
logger.warning("Cannot read Power Cell enrollment secret: %s", error)
return None
secret = secrets.token_hex(32)
try:
path.parent.mkdir(parents=True, exist_ok=True)
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(descriptor, "w", encoding="utf-8") as output:
output.write(secret + "\n")
except FileExistsError:
try:
stored = path.read_text(encoding="utf-8").strip()
except OSError as error:
logger.warning("Cannot read Power Cell enrollment secret: %s", error)
return None
if len(stored) < 32:
logger.warning("Cannot use the stored Power Cell enrollment secret")
return None
return stored
except OSError as error:
logger.warning("Cannot create Power Cell enrollment secret: %s", error)
return None
logger.info("Created a persistent Power Cell enrollment secret")
return secret


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("command", choices=["serve", "migrate"], default="serve", nargs="?")
Expand All @@ -31,7 +75,8 @@ def main():
logging.basicConfig(level=logging.INFO)
arguments.env_file = arguments.env_file.resolve()
os.chdir(API_ROOT)
migrate(Settings(_env_file=arguments.env_file))
settings = Settings(_env_file=arguments.env_file)
migrate(settings)
if arguments.command == "migrate":
return 0
if not (WEB_ROOT / "dist/index.html").is_file():
Expand All @@ -49,6 +94,9 @@ def main():
**os.environ,
"THRONG_ENV_FILE": str(arguments.env_file),
}
secret = ensure_enrollment_secret(settings)
if secret:
environment.setdefault("THRONG_ENROLLMENT_SECRET", secret)
stopping = threading.Event()
for signum in (signal.SIGTERM, signal.SIGINT):
signal.signal(signum, lambda *_: stopping.set())
Expand Down
9 changes: 8 additions & 1 deletion docs/deployment.md
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,14 @@ THRONG_ENROLLMENT_SECRET=<полученное значение>
Храните его вместе с БД в защищённых резервных копиях; при потере незавершённые
повторные `finish` перестанут возвращать тот же credential.

После изменения перезапустите `throng` и проверьте capabilities:
`deploy/activate.sh` при активации релиза создаёт секрет автоматически, если
его ещё нет в `/etc/throng/throng.env`. Кроме того, `deploy/run.py` при старте
без переменной создаёт `.enrollment-secret` рядом с папкой artifacts (в
production — `/var/lib/throng/.enrollment-secret`, права `0600`) и передаёт его
API. Поэтому обычный CI-деплой настраивает регистрацию без ручного изменения
сервера; файл нужно сохранять вместе с базой. Для уже работающего сервера без
нового деплоя добавьте секрет вручную и перезапустите сервис. После изменения
проверьте capabilities:

```sh
curl --fail https://api.mutating.tech/v1/agent-capabilities
Expand Down
9 changes: 8 additions & 1 deletion platform/api/throng_api/enrollment.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,14 @@ async def finish_enrollment(enrollment_id: UUID, request: Request, idempotency_k
)
values = {
key: request_values[key]
for key in ("name", "os", "architecture", "runtime", "disk_bytes", "isolation_modes")
for key in (
"name",
"os",
"architecture",
"runtime",
"disk_bytes",
"isolation_modes",
)
}
computer = Computer(
**values,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ def upgrade():

op.create_table(
"device_accounts",
sa.Column("device_id", sa.Uuid(as_uuid=False), sa.ForeignKey("devices.id"), primary_key=True),
sa.Column(
"device_id", sa.Uuid(as_uuid=False), sa.ForeignKey("devices.id"), primary_key=True
),
sa.Column("user_id", sa.Uuid(as_uuid=False), sa.ForeignKey("users.id"), primary_key=True),
sa.Column("first_seen_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("last_seen_at", sa.DateTime(timezone=True), nullable=False, index=True),
Expand Down Expand Up @@ -77,10 +79,7 @@ def upgrade():
{"device": device, "id": row.id},
)
exists = connection.execute(
sa.text(
"SELECT 1 FROM device_accounts "
"WHERE device_id = :device AND user_id = :user"
),
sa.text("SELECT 1 FROM device_accounts WHERE device_id = :device AND user_id = :user"),
{"device": device, "user": row.actor_id},
).first()
if not exists:
Expand Down Expand Up @@ -175,7 +174,9 @@ def downgrade():
batch.add_column(sa.Column("certificate_sha256", sa.String(length=64)))
batch.add_column(sa.Column("legacy_transfer_user_id", sa.Uuid(as_uuid=False)))
batch.add_column(
sa.Column("legacy_transfer_pending", sa.Boolean(), nullable=False, server_default=sa.false())
sa.Column(
"legacy_transfer_pending", sa.Boolean(), nullable=False, server_default=sa.false()
)
)
batch.create_foreign_key(
"fk_computers_legacy_transfer_user_id_users",
Expand Down
7 changes: 7 additions & 0 deletions tests/platform/api/deployment/test_activation.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +118,10 @@ def test_activation_preserves_the_database_and_current_release_on_failure(tmp_pa
assert any("migrate" in action for action in maintenance) == (failure != "backup")
assert len(starts) == 1
assert len(stops) == (2 if failure == "health" else 1)
if failure in {"", "protected"}:
secrets = [
line.split("=", 1)[1]
for line in server_env.read_text().splitlines()
if line.startswith("THRONG_ENROLLMENT_SECRET=")
]
assert len(secrets) == 1 and len(secrets[0]) == 64
41 changes: 41 additions & 0 deletions tests/platform/api/deployment/test_enrollment_secret.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""The supervisor can provision the registration secret without a server edit."""

import importlib.util
import stat
from pathlib import Path
from types import SimpleNamespace

ROOT = Path(__file__).resolve().parents[4]


def supervisor():
spec = importlib.util.spec_from_file_location("deploy_run", ROOT / "deploy/run.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module


def test_supervisor_creates_and_reuses_a_private_secret(tmp_path):
"""A code-only deployment gets a stable secret after the first restart."""
settings = SimpleNamespace(enrollment_secret=None, storage_path=tmp_path / "artifacts")
run = supervisor()

first = run.ensure_enrollment_secret(settings)
second = run.ensure_enrollment_secret(settings)

assert first == second
assert len(first) == 64
secret = tmp_path / ".enrollment-secret"
assert secret.read_text(encoding="utf-8").strip() == first
assert stat.S_IMODE(secret.stat().st_mode) == 0o600


def test_explicit_environment_secret_takes_precedence(tmp_path):
"""Production configuration remains authoritative when it is present."""
configured = "x" * 64
settings = SimpleNamespace(
enrollment_secret=configured, storage_path=tmp_path / "artifacts"
)

assert supervisor().ensure_enrollment_secret(settings) == configured
assert not (tmp_path / ".enrollment-secret").exists()
20 changes: 15 additions & 5 deletions tests/platform/api/e2e/powercell/test_connected_computers.py
Original file line number Diff line number Diff line change
Expand Up @@ -433,7 +433,9 @@ async def test_unlinking_an_ownership_returns_the_computer_to_the_unassigned_sta
page = (await api.get(PATH, params={"computer_id": computer_id})).json()
assert page["total"] == 1 and page["items"][0]["pool"] is None
assert (await api.get(f"/v1/computers/{computer_id}")).status_code == 200
confirmed = await api.patch(path, json={"company_id": company["id"], "expected_company_id": None})
confirmed = await api.patch(
path, json={"company_id": company["id"], "expected_company_id": None}
)
assert confirmed.status_code == 200 and confirmed.json()["company_id"] == company["id"]


Expand Down Expand Up @@ -557,7 +559,9 @@ async def test_move_preserves_signed_session_and_transfers_capacity(
session, agent_post = connected_worker
computer_id = session["computer_id"]
path = f"{PATH}/{computer_id}/pool"
assert (await api.patch(path, json={"company_id": None, "expected_company_id": None})).status_code == 200
assert (
await api.patch(path, json={"company_id": None, "expected_company_id": None})
).status_code == 200
before = clock.now
async with app.state.db.write() as database:
baseline = await database.get(AvailabilityBaseline, 1)
Expand Down Expand Up @@ -609,7 +613,9 @@ async def test_move_respects_live_permissions_and_busy_worker(
"""Revalidate source and destination roles and the current resource reservations."""
session, agent_post = connected_worker
path = f"{PATH}/{session['computer_id']}/pool"
assert (await api.patch(path, json={"company_id": None, "expected_company_id": None})).status_code == 200
assert (
await api.patch(path, json={"company_id": None, "expected_company_id": None})
).status_code == 200
created = await other_api.post("/v1/companies", json={"name": "Read-only pool"})
other_company = created.json()
joined = await other_api.post(
Expand Down Expand Up @@ -667,7 +673,9 @@ async def test_stale_native_mutation_cannot_revoke_key_or_overwrite_a_browser_mo
live, _ = connected_worker
computer_id = live["computer_id"]
path = f"{PATH}/{computer_id}/pool"
assert (await api.patch(path, json={"company_id": None, "expected_company_id": None})).status_code == 200
assert (
await api.patch(path, json={"company_id": None, "expected_company_id": None})
).status_code == 200
owner = next(
row
for row in (await api.get("/v1/computer-ownerships")).json()
Expand Down Expand Up @@ -722,7 +730,9 @@ async def test_delayed_browser_move_cannot_reapply_after_the_computer_returned_t
agent, _ = connected_worker
id_ = agent["computer_id"]
path = f"{PATH}/{id_}/pool"
assert (await api.patch(path, json={"company_id": None, "expected_company_id": None})).status_code == 200
assert (
await api.patch(path, json={"company_id": None, "expected_company_id": None})
).status_code == 200
initial = (await api.get(PATH, params={"computer_id": id_})).json()["items"][0]
next_pool = {"company_id": company["id"], "expected_company_id": None}
assert (
Expand Down
9 changes: 7 additions & 2 deletions tests/platform/api/e2e/powercell/test_owner_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
pytestmark = pytest.mark.anyio


async def test_account_recovery_revokes_credential_and_reuses_device(api, client, bound_device, user):
async def test_account_recovery_revokes_credential_and_reuses_device(
api, client, bound_device, user
):
"""Unbinding is idempotent, revokes the agent, and a fresh registration keeps the device."""
computer_id = bound_device.binding["computer_id"]
target = f"/v1/computers/{computer_id}/unbind"
Expand Down Expand Up @@ -46,7 +48,10 @@ async def test_account_recovery_revokes_credential_and_reuses_device(api, client
},
)
assert login.status_code == 200, login.text
headers = {"Authorization": "Bearer " + login.json()["access_token"], "Idempotency-Key": str(uuid4())}
headers = {
"Authorization": "Bearer " + login.json()["access_token"],
"Idempotency-Key": str(uuid4()),
}
payload = {
"device_id": bound_device.device_id,
"name": "Recovered Mac",
Expand Down
5 changes: 1 addition & 4 deletions tests/platform/api/integration/test_device_migration.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,7 @@ async def test_pending_installation_becomes_a_device_key(alembic_config, setting
{"id": str(enrollment_id)},
).one()
account = connection.execute(
text(
"SELECT 1 FROM device_accounts "
"WHERE device_id = :device AND user_id = :user"
),
text("SELECT 1 FROM device_accounts WHERE device_id = :device AND user_id = :user"),
{"device": device.id, "user": str(user_id)},
).one()
finally:
Expand Down
Loading