mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-10-26 21:26: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>
107 lines
4.7 KiB
Python
107 lines
4.7 KiB
Python
"""The Helm chart generates and injects ``DEER_FLOW_CREDENTIALS_KEY``.
|
|
|
|
Every gateway Pod must encrypt and decrypt stored credentials with one key, so
|
|
the chart generates a Fernet key into the app Secret once, preserves it across
|
|
upgrades through ``lookup`` like ``AUTH_JWT_SECRET``, and injects it into the
|
|
gateway. Sprig's ``randBytes`` emits standard base64; Fernet keys use the
|
|
urlsafe alphabet, so the template translates ``+``/``/`` to ``-``/``_``.
|
|
|
|
The ``helm template`` tests skip when helm is not installed; CI's runner has it.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
import yaml
|
|
from cryptography.fernet import Fernet
|
|
|
|
from deerflow.config.credentials_key import CREDENTIALS_KEY_ENV_VAR, parse_credentials_keys
|
|
|
|
REPO_ROOT = Path(__file__).resolve().parents[2]
|
|
CHART = REPO_ROOT / "deploy" / "helm" / "deer-flow"
|
|
APP_SECRET_TEMPLATE = CHART / "templates" / "secret-app.yaml"
|
|
README = CHART / "README.md"
|
|
NOTES = CHART / "templates" / "NOTES.txt"
|
|
VALUES = CHART / "values.yaml"
|
|
|
|
_FERNET_KEY = re.compile(r"[A-Za-z0-9_-]{43}=")
|
|
|
|
|
|
def _render_chart(*settings: str) -> list[dict]:
|
|
helm = shutil.which("helm")
|
|
if helm is None:
|
|
pytest.skip("helm is unavailable")
|
|
command = [helm, "template", "deer-flow", str(CHART)]
|
|
for setting in settings:
|
|
command.extend(["--set", setting])
|
|
rendered = subprocess.run(command, check=True, capture_output=True, text=True).stdout
|
|
return [document for document in yaml.safe_load_all(rendered) if isinstance(document, dict)]
|
|
|
|
|
|
def _app_secret(documents: list[dict]) -> dict:
|
|
return next(document for document in documents if document.get("kind") == "Secret" and document["metadata"]["name"].endswith("-app"))
|
|
|
|
|
|
def _gateway(documents: list[dict]) -> dict:
|
|
deployment = next(document for document in documents if document.get("kind") == "Deployment" and document["metadata"]["name"].endswith("-gateway"))
|
|
return next(container for container in deployment["spec"]["template"]["spec"]["containers"] if container["name"] == "gateway")
|
|
|
|
|
|
def _env(container: dict) -> dict[str, dict]:
|
|
return {item["name"]: item for item in container["env"]}
|
|
|
|
|
|
def test_rendered_app_secret_carries_a_valid_fernet_key() -> None:
|
|
key = _app_secret(_render_chart())["stringData"][CREDENTIALS_KEY_ENV_VAR]
|
|
|
|
assert _FERNET_KEY.fullmatch(key), "must be urlsafe base64 of 32 bytes"
|
|
assert len(base64.urlsafe_b64decode(key)) == 32
|
|
Fernet(key)
|
|
assert parse_credentials_keys(key) == [key], "the Gateway's own parser must accept the generated key"
|
|
|
|
|
|
def test_each_fresh_render_generates_an_independent_key() -> None:
|
|
"""randBytes, not a constant: two installs must not share a key."""
|
|
first = _app_secret(_render_chart())["stringData"][CREDENTIALS_KEY_ENV_VAR]
|
|
second = _app_secret(_render_chart())["stringData"][CREDENTIALS_KEY_ENV_VAR]
|
|
assert first != second
|
|
|
|
|
|
def test_app_secret_template_preserves_the_key_across_upgrades() -> None:
|
|
"""``helm template`` never sees ``lookup`` results, so pin the preservation in the source."""
|
|
template = APP_SECRET_TEMPLATE.read_text(encoding="utf-8")
|
|
assert f'index $prev.data "{CREDENTIALS_KEY_ENV_VAR}"' in template, "a regenerated key would make every stored credential unreadable"
|
|
assert f"{CREDENTIALS_KEY_ENV_VAR}: {{{{ $credentialsKey | quote }}}}" in template
|
|
assert 'randBytes 32 | replace "+" "-" | replace "/" "_"' in template
|
|
|
|
|
|
@pytest.mark.parametrize("replicas", ["1", "3"])
|
|
def test_gateway_reads_the_key_from_the_app_secret(replicas: str) -> None:
|
|
gateway = _gateway(_render_chart(f"gateway.replicas={replicas}"))
|
|
reference = _env(gateway)[CREDENTIALS_KEY_ENV_VAR]["valueFrom"]["secretKeyRef"]
|
|
|
|
assert reference["name"].endswith("-app")
|
|
assert reference["key"] == CREDENTIALS_KEY_ENV_VAR
|
|
# Optional so a user-managed existingAppSecret without the key still boots: the
|
|
# Gateway's own startup gate refuses a multi-instance deployment that stores
|
|
# credentials without it, and leaves the others alone.
|
|
assert reference["optional"] is True
|
|
|
|
|
|
def test_existing_app_secret_is_honored_for_the_key() -> None:
|
|
documents = _render_chart("existingAppSecret=my-app-secret")
|
|
assert not any(document.get("kind") == "Secret" and document["metadata"]["name"].endswith("-app") for document in documents)
|
|
assert _env(_gateway(documents))[CREDENTIALS_KEY_ENV_VAR]["valueFrom"]["secretKeyRef"]["name"] == "my-app-secret"
|
|
|
|
|
|
def test_docs_mention_the_key() -> None:
|
|
for document in (README, NOTES, VALUES):
|
|
assert CREDENTIALS_KEY_ENV_VAR in document.read_text(encoding="utf-8"), document.name
|
|
assert ".credentials_key" in README.read_text(encoding="utf-8"), "the README must say how to keep an auto-generated key"
|