mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-10-27 05:30:39 +00:00
* fix(security): add DEER_FLOW_CREDENTIALS_KEY for at-rest credential encryption
There was no at-rest encryption key. ChannelCredentialCipher had no
production caller: the channel service, the scheduled-task notification
outbox and the channel-connections router all built
ChannelConnectionRepository without a cipher, so store_credentials refused
(RuntimeError) and get_credentials always returned None.
- New harness module deerflow.config.credentials_key: env-only
DEER_FLOW_CREDENTIALS_KEY (comma-separated Fernet keys; first encrypts,
all decrypt via MultiFernet), CredentialsCipher with encrypt_text /
decrypt_text / rotate_text, a fernet:v2: prefix with legacy fernet:v1:
values still readable, and get_credentials_cipher() as the process-wide
entry point. Malformed keys are refused without echoing key material.
Without the variable a single instance generates
{base_dir}/.credentials_key. Never derived from AUTH_JWT_SECRET.
- New deerflow.config.secret_file.read_or_create_secret_file: O_EXCL
create (0600) plus read-back with a bounded settle window, shared by
.credentials_key, .jwt_secret (fixes two replicas cold-starting on a
shared volume keeping different JWT secrets) and the managed-model key.
- ChannelCredentialCipher now builds on CredentialsCipher (same
constructors); the Gateway loads the cipher off the event loop at
startup when channel_connections is enabled and passes it to every
ChannelConnectionRepository. Undecryptable values stay "missing + warn".
- Startup gate: a malformed key stops startup in any topology; a declared
multi-instance deployment with channel_connections enabled and no key
is refused. Plain multi-worker shares the generated file and is allowed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(deploy): generate and inject DEER_FLOW_CREDENTIALS_KEY in Helm, compose and deploy.sh
- Helm: the app Secret generates a Fernet key (randBytes 32 translated to
the urlsafe alphabet) and preserves it across upgrades via lookup like
AUTH_JWT_SECRET; the gateway reads it through an optional secretKeyRef
so a user-managed existingAppSecret without it still boots (the Gateway
gate refuses only multi-instance deployments that store credentials).
README, NOTES and values document backup, rotation and existingAppSecret.
- scripts/deploy.sh resolves the key shell -> .env -> persisted file ->
generated, persisting it as $DEER_FLOW_HOME/.credentials_key (0600,
noclobber/O_EXCL with read-back): the same file the Gateway generates in
its runtime home, so either side's key is the one both keep.
- Both compose files pass DEER_FLOW_CREDENTIALS_KEY=${...:-} to the gateway.
- .env.example entry with a generation hint; README and CHANGELOG notes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(security): make abandoned secret-file replacement single-winner
A rename is last-writer-wins, so replicas that restart together and all
find the same abandoned empty secret file could each replace it and keep
a different value. The process that exclusively creates
<name>.replacing now owns the replacement, re-checks the file is still
empty, and publishes by renaming the claim over it; peers wait for that
value, bounded so a crashed replacer cannot block startup forever.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs(changelog): link DEER_FLOW_CREDENTIALS_KEY entries to #6611
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(security): name the setting that turns off a credentials-key consumer
The multi-instance refusal ended with "or disable
channel_connections.enabled=true"; it now says "or set
channel_connections.enabled=false".
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(security): never expose a secret file before its value is written
O_EXCL published the name before its content, so a creator that stalled
mid-write left an empty file a peer replaced after the settle window; the
resumed creator then returned a value nobody persisted, or deleted the
peer's valid file when its own write failed. Creators now write and sync
a private temporary file and hard-link it to the name, which fails if
the name exists; a failed creator only removes its own temporary file.
Filesystems without hard links publish through the same single-winner
<name>.replacing claim that replaces abandoned empty files, so creation
and replacement are serialized there.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(models): recover an empty managed-model key when no catalog exists
An interrupted first save could leave an empty key file; every later save
then passed empty bytes to Fernet and the endpoint returned 503 until the
file was removed by hand. An empty key with no catalog encrypted nothing,
so it now goes through the secret-file recovery path; next to an existing
catalog it is still refused.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(docker): pass the dotenv DEER_FLOW_CREDENTIALS_KEY through make docker-start
scripts/docker.sh runs Compose from docker/ without --env-file, so the dev
gateway's DEER_FLOW_CREDENTIALS_KEY=${DEER_FLOW_CREDENTIALS_KEY:-} entry
interpolated to empty and overrode the key the checkout .env supplied via
env_file. Export it from the dotenv like AUTH_TRUSTED_PROXIES.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
352 lines
13 KiB
Python
352 lines
13 KiB
Python
"""Exclusive-create helper for small secret files shared by concurrent processes.
|
|
|
|
Gateway replicas that share a runtime home (a Helm ``ReadWriteMany`` volume, a
|
|
compose bind mount, or several uvicorn workers of one host) cold-start at the
|
|
same time and each find no secret file yet. A read-then-``O_TRUNC`` write lets
|
|
every one of them keep a different value -- for ``.jwt_secret`` that is two
|
|
replicas signing sessions with different keys, for ``.credentials_key`` it is
|
|
credentials one replica cannot decrypt. ``read_or_create_secret_file`` creates
|
|
with ``O_EXCL`` and reads the winner's value back instead.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import os
|
|
import threading
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from deerflow.config.secret_file import InvalidSecretFileError, read_or_create_secret_file
|
|
|
|
|
|
def test_creates_a_missing_file_with_owner_only_permissions(tmp_path: Path) -> None:
|
|
path = tmp_path / "nested" / ".secret"
|
|
|
|
value = read_or_create_secret_file(path, lambda: "generated-value")
|
|
|
|
assert value == "generated-value"
|
|
assert path.read_text(encoding="utf-8") == "generated-value"
|
|
if os.name == "posix":
|
|
assert path.stat().st_mode & 0o777 == 0o600
|
|
|
|
|
|
def test_reuses_an_existing_value_without_generating(tmp_path: Path) -> None:
|
|
path = tmp_path / ".secret"
|
|
path.write_text("existing-value\n", encoding="utf-8")
|
|
|
|
def generate() -> str:
|
|
raise AssertionError("an existing secret must never be regenerated")
|
|
|
|
assert read_or_create_secret_file(path, generate) == "existing-value"
|
|
assert path.read_text(encoding="utf-8") == "existing-value\n"
|
|
|
|
|
|
def test_a_peer_that_publishes_first_wins(tmp_path: Path) -> None:
|
|
"""Deterministic race: the peer creates the file between our existence check and our create.
|
|
|
|
A read-then-truncating write would overwrite the peer's value and return
|
|
our own, leaving the two processes on different secrets.
|
|
"""
|
|
path = tmp_path / ".secret"
|
|
|
|
def generate() -> str:
|
|
path.write_text("peer-value", encoding="utf-8")
|
|
return "our-value"
|
|
|
|
assert read_or_create_secret_file(path, generate) == "peer-value"
|
|
assert path.read_text(encoding="utf-8") == "peer-value"
|
|
|
|
|
|
def test_concurrent_creators_converge_on_one_value(tmp_path: Path) -> None:
|
|
path = tmp_path / ".secret"
|
|
workers = 16
|
|
barrier = threading.Barrier(workers)
|
|
results: list[str] = []
|
|
errors: list[BaseException] = []
|
|
lock = threading.Lock()
|
|
|
|
def run(index: int) -> None:
|
|
try:
|
|
barrier.wait(timeout=10)
|
|
value = read_or_create_secret_file(path, lambda: f"value-{index}")
|
|
with lock:
|
|
results.append(value)
|
|
except BaseException as exc: # noqa: BLE001 - surface every worker failure
|
|
with lock:
|
|
errors.append(exc)
|
|
|
|
threads = [threading.Thread(target=run, args=(index,)) for index in range(workers)]
|
|
for thread in threads:
|
|
thread.start()
|
|
for thread in threads:
|
|
thread.join(timeout=30)
|
|
|
|
assert not errors
|
|
assert len(results) == workers
|
|
assert len(set(results)) == 1, f"creators diverged: {sorted(set(results))}"
|
|
assert path.read_text(encoding="utf-8") == results[0]
|
|
|
|
|
|
def test_waits_for_a_peer_that_has_created_but_not_yet_written(tmp_path: Path) -> None:
|
|
"""Older releases published the name before its content: an empty file may be one of them mid-write."""
|
|
path = tmp_path / ".secret"
|
|
path.touch()
|
|
writer = threading.Timer(0.1, lambda: path.write_text("late-value", encoding="utf-8"))
|
|
writer.start()
|
|
try:
|
|
value = read_or_create_secret_file(path, lambda: "our-value", settle_seconds=5)
|
|
finally:
|
|
writer.join()
|
|
|
|
assert value == "late-value"
|
|
assert path.read_text(encoding="utf-8") == "late-value"
|
|
|
|
|
|
def test_retries_a_partially_written_value_that_fails_validation(tmp_path: Path) -> None:
|
|
path = tmp_path / ".secret"
|
|
path.write_text("0123", encoding="utf-8")
|
|
|
|
def validate(value: str) -> None:
|
|
if len(value) != 10:
|
|
raise ValueError("incomplete")
|
|
|
|
writer = threading.Timer(0.1, lambda: path.write_text("0123456789", encoding="utf-8"))
|
|
writer.start()
|
|
try:
|
|
value = read_or_create_secret_file(path, lambda: "abcdefghij", validate=validate, settle_seconds=5)
|
|
finally:
|
|
writer.join()
|
|
|
|
assert value == "0123456789"
|
|
|
|
|
|
def test_an_abandoned_empty_file_is_replaced(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
|
|
"""A crash between create and write (or an older release's truncating write) leaves an empty file.
|
|
|
|
Nothing can have been signed or encrypted with an empty secret, so once the
|
|
settle window passes it is replaced instead of failing startup forever.
|
|
"""
|
|
path = tmp_path / ".secret"
|
|
path.touch()
|
|
|
|
with caplog.at_level(logging.WARNING, logger="deerflow.config.secret_file"):
|
|
value = read_or_create_secret_file(path, lambda: "fresh-value", settle_seconds=0.05)
|
|
|
|
assert value == "fresh-value"
|
|
assert path.read_text(encoding="utf-8") == "fresh-value"
|
|
assert any(str(path) in record.getMessage() for record in caplog.records)
|
|
if os.name == "posix":
|
|
assert path.stat().st_mode & 0o777 == 0o600
|
|
|
|
|
|
def test_concurrent_replacers_of_an_abandoned_empty_file_converge(tmp_path: Path) -> None:
|
|
"""Replicas restarting together after a crash all find the same abandoned empty file.
|
|
|
|
The replacement is a last-writer-wins rename, so a replacer must not trust
|
|
its own value until peers that decided to replace in the same window have
|
|
written theirs.
|
|
"""
|
|
path = tmp_path / ".secret"
|
|
path.touch()
|
|
workers = 8
|
|
barrier = threading.Barrier(workers)
|
|
results: list[str] = []
|
|
errors: list[BaseException] = []
|
|
lock = threading.Lock()
|
|
|
|
def run(index: int) -> None:
|
|
def generate() -> str:
|
|
# Stagger the replacements so an early replacer would otherwise
|
|
# read back its own value before a later one overwrites it.
|
|
threading.Event().wait(0.01 * index)
|
|
return f"value-{index}"
|
|
|
|
try:
|
|
barrier.wait(timeout=10)
|
|
value = read_or_create_secret_file(path, generate, settle_seconds=0.2)
|
|
with lock:
|
|
results.append(value)
|
|
except BaseException as exc: # noqa: BLE001 - surface every worker failure
|
|
with lock:
|
|
errors.append(exc)
|
|
|
|
threads = [threading.Thread(target=run, args=(index,)) for index in range(workers)]
|
|
for thread in threads:
|
|
thread.start()
|
|
for thread in threads:
|
|
thread.join(timeout=30)
|
|
|
|
assert not errors
|
|
assert len(results) == workers
|
|
assert len(set(results)) == 1, f"replacers diverged: {sorted(set(results))}"
|
|
assert path.read_text(encoding="utf-8") == results[0]
|
|
|
|
|
|
def test_waits_for_a_peer_that_holds_the_replacement_claim(tmp_path: Path) -> None:
|
|
path = tmp_path / ".secret"
|
|
path.touch()
|
|
claim = tmp_path / ".secret.replacing"
|
|
claim.write_text("peer-value", encoding="utf-8")
|
|
publisher = threading.Timer(0.3, lambda: os.replace(claim, path))
|
|
publisher.start()
|
|
try:
|
|
value = read_or_create_secret_file(path, lambda: "our-value", settle_seconds=0.05)
|
|
finally:
|
|
publisher.join()
|
|
|
|
assert value == "peer-value"
|
|
assert not claim.exists()
|
|
|
|
|
|
def test_a_claim_left_by_a_crashed_replacer_is_refused_after_a_bounded_wait(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
monkeypatch.setattr("deerflow.config.secret_file._CLAIM_WAIT_SECONDS", 0.2)
|
|
path = tmp_path / ".secret"
|
|
path.touch()
|
|
claim = tmp_path / ".secret.replacing"
|
|
claim.touch()
|
|
|
|
with pytest.raises(InvalidSecretFileError, match="interrupted creation"):
|
|
read_or_create_secret_file(path, lambda: "our-value", settle_seconds=0.05)
|
|
|
|
assert path.read_text(encoding="utf-8") == ""
|
|
|
|
|
|
def test_a_late_replacer_does_not_overwrite_a_published_replacement(tmp_path: Path) -> None:
|
|
"""A process that saw the empty file before a peer's replacement landed must back off."""
|
|
path = tmp_path / ".secret"
|
|
path.write_text("peer-value", encoding="utf-8")
|
|
from deerflow.config.secret_file import _publish_under_claim
|
|
|
|
assert _publish_under_claim(path, lambda: "late-value", replace_empty=True) is True
|
|
assert path.read_text(encoding="utf-8") == "peer-value"
|
|
assert not (tmp_path / ".secret.replacing").exists()
|
|
|
|
|
|
def test_a_persistently_invalid_file_is_refused_without_echoing_it(tmp_path: Path) -> None:
|
|
"""A non-empty value may be the only copy of a key that encrypted data: never overwrite it."""
|
|
path = tmp_path / ".secret"
|
|
path.write_text("operator-typo-in-the-key", encoding="utf-8")
|
|
|
|
def validate(value: str) -> None:
|
|
raise ValueError(f"bad value {value}")
|
|
|
|
with pytest.raises(InvalidSecretFileError) as exc_info:
|
|
read_or_create_secret_file(path, lambda: "replacement", validate=validate, settle_seconds=0.05)
|
|
|
|
assert str(path) in str(exc_info.value)
|
|
assert "operator-typo-in-the-key" not in str(exc_info.value)
|
|
assert exc_info.value.__cause__ is None, "the validator's message may quote the value"
|
|
assert path.read_text(encoding="utf-8") == "operator-typo-in-the-key"
|
|
|
|
|
|
def test_a_failed_write_leaves_no_empty_file_for_peers_to_wait_on(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
path = tmp_path / ".secret"
|
|
|
|
def broken_write(_fd: int, _data: bytes) -> None:
|
|
raise OSError("disk full")
|
|
|
|
monkeypatch.setattr("deerflow.config.secret_file._write_all", broken_write)
|
|
|
|
with pytest.raises(OSError, match="disk full"):
|
|
read_or_create_secret_file(path, lambda: "value")
|
|
|
|
assert not path.exists()
|
|
|
|
|
|
def _pause_one_creator(monkeypatch: pytest.MonkeyPatch, thread_name: str, *, fail: bool = False) -> tuple[threading.Event, threading.Event]:
|
|
"""Hold ``thread_name`` inside its secret write until released; the other threads write normally."""
|
|
import deerflow.config.secret_file as secret_file
|
|
|
|
entered = threading.Event()
|
|
release = threading.Event()
|
|
original_write_all = secret_file._write_all
|
|
|
|
def write_all(fd: int, data: bytes) -> None:
|
|
if threading.current_thread().name == thread_name:
|
|
entered.set()
|
|
assert release.wait(timeout=10)
|
|
if fail:
|
|
raise OSError("disk full")
|
|
original_write_all(fd, data)
|
|
|
|
monkeypatch.setattr(secret_file, "_write_all", write_all)
|
|
return entered, release
|
|
|
|
|
|
@pytest.mark.parametrize("fail", [False, True], ids=["paused-then-writes", "paused-then-fails"])
|
|
def test_a_paused_creator_never_exposes_a_file_a_peer_could_replace(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, fail: bool) -> None:
|
|
"""A creator stalled mid-write must not leave a visible empty file behind.
|
|
|
|
Otherwise a peer treats it as abandoned after the settle window and
|
|
publishes its own value; the resumed creator then returns a value nobody
|
|
persisted, or (when its write fails) deletes the peer's valid file.
|
|
"""
|
|
path = tmp_path / ".secret"
|
|
entered, release = _pause_one_creator(monkeypatch, "first", fail=fail)
|
|
results: dict[str, str | BaseException] = {}
|
|
|
|
def run(name: str) -> None:
|
|
try:
|
|
results[name] = read_or_create_secret_file(path, lambda: f"{name}-value", settle_seconds=0.05)
|
|
except BaseException as exc: # noqa: BLE001 - asserted below
|
|
results[name] = exc
|
|
|
|
first = threading.Thread(target=run, args=("first",), name="first")
|
|
first.start()
|
|
assert entered.wait(timeout=10)
|
|
peer = threading.Thread(target=run, args=("peer",), name="peer")
|
|
peer.start()
|
|
peer.join(timeout=10)
|
|
release.set()
|
|
first.join(timeout=10)
|
|
|
|
assert results["peer"] == "peer-value"
|
|
assert path.read_text(encoding="utf-8") == "peer-value", "the peer's published value must survive"
|
|
if fail:
|
|
assert isinstance(results["first"], OSError)
|
|
else:
|
|
assert results["first"] == "peer-value", "the resumed creator must adopt the persisted value"
|
|
|
|
|
|
def test_creation_without_hard_links_still_converges(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""Filesystems without hard links (SMB shares) publish through the replacement claim instead."""
|
|
import errno
|
|
|
|
def no_hard_links(*_args, **_kwargs):
|
|
raise OSError(errno.EPERM, "Operation not permitted")
|
|
|
|
monkeypatch.setattr(os, "link", no_hard_links)
|
|
path = tmp_path / ".secret"
|
|
workers = 8
|
|
barrier = threading.Barrier(workers)
|
|
results: list[str] = []
|
|
lock = threading.Lock()
|
|
|
|
def run(index: int) -> None:
|
|
barrier.wait(timeout=10)
|
|
value = read_or_create_secret_file(path, lambda: f"value-{index}", settle_seconds=0.05)
|
|
with lock:
|
|
results.append(value)
|
|
|
|
threads = [threading.Thread(target=run, args=(index,)) for index in range(workers)]
|
|
for thread in threads:
|
|
thread.start()
|
|
for thread in threads:
|
|
thread.join(timeout=30)
|
|
|
|
assert len(results) == workers
|
|
assert len(set(results)) == 1, f"creators diverged: {sorted(set(results))}"
|
|
assert path.read_text(encoding="utf-8") == results[0]
|
|
assert not (tmp_path / ".secret.replacing").exists()
|
|
if os.name == "posix":
|
|
assert path.stat().st_mode & 0o777 == 0o600
|
|
|
|
|
|
def test_no_temporary_files_are_left_behind(tmp_path: Path) -> None:
|
|
path = tmp_path / ".secret"
|
|
read_or_create_secret_file(path, lambda: "value")
|
|
|
|
assert sorted(entry.name for entry in tmp_path.iterdir()) == [".secret"]
|