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
11 changes: 8 additions & 3 deletions scripts/cloudru-app-host/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,14 @@ cloud-init в `/etc/bro/deployd.json`; сам `DEPLOY_SIGNING_KEY` на VM не
Ключи оператора (`~/.bro-app-host` без `build/` и `vendor/`, `~/.bro-code-host`)
есть только в контейнере сессии и на VM. `host.py state save` после каждой их
смены кладёт их в Object Storage (`operator/state.bin`): AES-256-CBC `openssl`
и HMAC-SHA256, ключи — из `CLOUDRU_KEY_SECRET` окружения. Новая сессия
начинает с `host.py state restore` (файлы, что уже есть, не трогает;
`--force` — заменить). После смены ключа Cloud.ru — снова `state save`.
и HMAC-SHA256, ключи — из `OPERATOR_STATE_KEY`, а если его нет, из прежнего
`CLOUDRU_KEY_SECRET` (имя с времён Cloud.ru: состояние, сохранённое тогда,
открывается только им) и, если нет и его, из `S3_SECRET_ACCESS_KEY`, с которым
сессия ходит в бакет. `state save` запечатывает первым из заданных, `state
restore` перебирает все. Отдельный секрет не нужен, но последний вариант
защищает не больше, чем ключ бакета. Новая сессия начинает с `host.py state
restore` (файлы, что уже есть, не трогает; `--force` — заменить). После
смены ключа — снова `state save`.

`host.py vendor` качает по пинам `vendor.json` Caddy (GitHub), Node
(nodejs.org) и пакеты `libpq5`, `postgresql-client-common`,
Expand Down
38 changes: 26 additions & 12 deletions scripts/cloudru-app-host/host.py
Original file line number Diff line number Diff line change
Expand Up @@ -1079,8 +1079,11 @@ def given(name):

# DEPLOY_SIGNING_KEY, the consoles' passwords, BACKUP_ENCRYPTION_KEY and the env files live in this session's
# container and on the VMs only (BETTER_AUTH_SECRET and SECRET_ENCRYPTION_KEY too, once Vercel Blob is gone).
# Sealed under a key derived from CLOUDRU_KEY_SECRET, which the environment keeps for every session: whoever
# has it controls the project anyway. A rotated Cloud.ru key needs `state save` again.
# Sealed under a key derived from OPERATOR_STATE_KEY; sessions without it use the legacy CLOUDRU_KEY_SECRET (the name
# is from the days of Cloud.ru, and the state saved then opens only with it) and, with neither, the Object Storage
# secret key the session reaches the bucket with. Whoever has any of them reaches the bucket anyway, so the last
# one costs a session no secret of its own, but protects nothing beyond the bucket's own keys. `state save` seals
# under the first one set; `state restore` tries each in turn, so a state sealed under the legacy key still opens.
STATE_KEY = "operator/state.bin"
STATE_MAGIC = b"BRO-OPERATOR-STATE-1\n"
CODE_HOST_STATE = Path(os.environ.get("BRO_CODE_HOST_DIR", Path.home() / ".bro-code-host"))
Expand All @@ -1097,6 +1100,12 @@ def derive(label):
return derive("encrypt"), bytes.fromhex(derive("mac"))


def state_secrets():
"""The secrets a sealed state may be under, the one `state save` uses first."""
names = ("OPERATOR_STATE_KEY", "CLOUDRU_KEY_SECRET", "S3_SECRET_ACCESS_KEY")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: state_secrets treats a lone S3_SECRET_ACCESS_KEY as usable, but s3.py selects S3 credentials only when all four S3_* settings exist. With a partial S3 setup and no Cloud secret, cmd_state passes the guard then crashes with KeyError; gate this fallback on s3.PROVIDER or validate the complete S3 configuration.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At scripts/cloudru-app-host/host.py, line 1105:

<comment>`state_secrets` treats a lone `S3_SECRET_ACCESS_KEY` as usable, but `s3.py` selects S3 credentials only when all four `S3_*` settings exist. With a partial S3 setup and no Cloud secret, `cmd_state` passes the guard then crashes with `KeyError`; gate this fallback on `s3.PROVIDER` or validate the complete S3 configuration.</comment>

<file context>
@@ -1097,6 +1100,12 @@ def derive(label):
 
+def state_secrets():
+    """The secrets a sealed state may be under, the one `state save` uses first."""
+    names = ("OPERATOR_STATE_KEY", "CLOUDRU_KEY_SECRET", "S3_SECRET_ACCESS_KEY")
+    return [os.environ[name] for name in names if os.environ.get(name, "").strip()]
+
</file context>
Suggested change
names = ("OPERATOR_STATE_KEY", "CLOUDRU_KEY_SECRET", "S3_SECRET_ACCESS_KEY")
names = ("OPERATOR_STATE_KEY", "CLOUDRU_KEY_SECRET")
if s3.PROVIDER:
names += ("S3_SECRET_ACCESS_KEY",)

return [os.environ[name] for name in names if os.environ.get(name, "").strip()]


def seal(data, secret):
"""AES-256-CBC (openssl, PBKDF2) then HMAC-SHA256 over the ciphertext: the stdlib has no AES."""
passphrase, mac_key = state_keys(secret)
Expand All @@ -1112,13 +1121,18 @@ def seal(data, secret):
return STATE_MAGIC + hmac.new(mac_key, cipher, hashlib.sha256).digest() + cipher


def unseal(blob, secret):
passphrase, mac_key = state_keys(secret)
def unseal(blob, secrets):
"""The state, opened with the first of `secrets` it is sealed under (one secret is accepted too)."""
if not blob.startswith(STATE_MAGIC):
sys.exit("not a sealed operator state")
tag, cipher = blob[len(STATE_MAGIC):len(STATE_MAGIC) + 32], blob[len(STATE_MAGIC) + 32:]
if not hmac.compare_digest(tag, hmac.new(mac_key, cipher, hashlib.sha256).digest()):
sys.exit("the operator state does not open with this CLOUDRU_KEY_SECRET (rotated since `state save`?)")
for secret in [secrets] if isinstance(secrets, str) else secrets:
passphrase, mac_key = state_keys(secret)
if hmac.compare_digest(tag, hmac.new(mac_key, cipher, hashlib.sha256).digest()):
break
else:
sys.exit("the operator state does not open with OPERATOR_STATE_KEY, CLOUDRU_KEY_SECRET or S3_SECRET_ACCESS_KEY "

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Changing this message leaves the existing HostCliTest failing: its wrong-key and tamper assertions still require does not open with this CLOUDRU_KEY_SECRET. Update those assertions before merging.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At scripts/cloudru-app-host/host.py, line 1134:

<comment>Changing this message leaves the existing `HostCliTest` failing: its wrong-key and tamper assertions still require `does not open with this CLOUDRU_KEY_SECRET`. Update those assertions before merging.</comment>

<file context>
@@ -1112,13 +1121,18 @@ def seal(data, secret):
+        if hmac.compare_digest(tag, hmac.new(mac_key, cipher, hashlib.sha256).digest()):
+            break
+    else:
+        sys.exit("the operator state does not open with OPERATOR_STATE_KEY, CLOUDRU_KEY_SECRET or S3_SECRET_ACCESS_KEY "
+                 "(rotated since `state save`?)")
     read, write = os.pipe()
</file context>

"(rotated since `state save`?)")
read, write = os.pipe()
os.write(write, passphrase.encode() + b"\n")
os.close(write)
Expand Down Expand Up @@ -1184,13 +1198,13 @@ def state_roots():


def cmd_state(args):
secret = os.environ.get("CLOUDRU_KEY_SECRET", "")
if not secret.strip():
sys.exit("CLOUDRU_KEY_SECRET is required")
secrets = state_secrets()
if not secrets:
sys.exit("OPERATOR_STATE_KEY (or CLOUDRU_KEY_SECRET, or S3_SECRET_ACCESS_KEY) is required")
if args.action == "save":
data = state_archive(state_roots())
sealed = seal(data, secret)
if unseal(sealed, secret) != data:
sealed = seal(data, secrets[0])
if unseal(sealed, secrets[:1]) != data:
sys.exit("the sealed state does not open again: nothing uploaded")
with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as tar:
count = len(tar.getmembers())
Expand All @@ -1200,7 +1214,7 @@ def cmd_state(args):
code, body = s3.send(urllib.request.Request(s3.presign("GET", STATE_KEY, 600)))
if code != 200:
sys.exit(f"get {STATE_KEY}: {code}")
written, kept = restore_archive(unseal(body, secret), state_roots(), force=args.force)
written, kept = restore_archive(unseal(body, secrets), state_roots(), force=args.force)
print(f"restored {written} files, kept {kept} already here (--force replaces them)")


Expand Down
15 changes: 13 additions & 2 deletions scripts/cloudru-app-host/host/test_host.py
Original file line number Diff line number Diff line change
Expand Up @@ -1601,14 +1601,25 @@ def test_the_operator_state_seals_and_opens_only_with_its_key(self):
self.assertNotIn(b"keys", sealed)
# A pasted key's whitespace does not change the key.
self.assertEqual(self.host.unseal(sealed, " cloud-rusecret "), b"keys")
with self.assertRaisesRegex(SystemExit, "does not open with this CLOUDRU_KEY_SECRET"):
with self.assertRaisesRegex(SystemExit, "does not open with OPERATOR_STATE_KEY"):
self.host.unseal(sealed, "another secret")
tampered = sealed[:-1] + bytes([sealed[-1] ^ 1])
with self.assertRaisesRegex(SystemExit, "does not open with this CLOUDRU_KEY_SECRET"):
with self.assertRaisesRegex(SystemExit, "does not open with OPERATOR_STATE_KEY"):
self.host.unseal(tampered, "cloud-ru secret")
# A state sealed under the legacy key still opens when a newer key is tried first.
self.assertEqual(self.host.unseal(sealed, ["new key", "cloud-ru secret"]), b"keys")
with self.assertRaisesRegex(SystemExit, "not a sealed operator state"):
self.host.unseal(b"plain", "cloud-ru secret")

def test_the_operator_state_key_comes_from_the_first_secret_that_is_set(self):
names = ("OPERATOR_STATE_KEY", "CLOUDRU_KEY_SECRET", "S3_SECRET_ACCESS_KEY")
with mock.patch.dict(os.environ, {name: "" for name in names}):
self.assertEqual(self.host.state_secrets(), [])
with mock.patch.dict(os.environ, {"S3_SECRET_ACCESS_KEY": "s3", "CLOUDRU_KEY_SECRET": "legacy"}):
self.assertEqual(self.host.state_secrets(), ["legacy", "s3"])
with mock.patch.dict(os.environ, {"OPERATOR_STATE_KEY": "new"}):
self.assertEqual(self.host.state_secrets(), ["new", "legacy", "s3"])

def test_the_operator_state_keeps_keys_not_builds_and_restores_without_overwriting(self):
source, target = Path(tempfile.mkdtemp()), Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, source)
Expand Down
Loading