Skip to content

fix(storage): fail fast instead of storing plaintext when crypto config is broken - #17753

Closed
LHMQ878 wants to merge 1602 commits into
infiniflow:mainfrom
LHMQ878:fix/crypto-storage-no-plaintext-fallback
Closed

LHMQ878 wants to merge 1602 commits into
infiniflow:mainfrom
LHMQ878:fix/crypto-storage-no-plaintext-fallback

Conversation

@LHMQ878

@LHMQ878 LHMQ878 commented Aug 3, 2026

Copy link
Copy Markdown

Summary

Fixes #17752.

RAGFLOW_CRYPTO_ENABLED=true is a request for encryption at rest. Today, if the crypto configuration is broken, init_settings() logs one line and assigns the unencrypted storage impl, so documents are written in the clear while the deployment looks healthy. This PR removes that fallback, fixes the two defaults in create_encrypted_storage that made the broken-config case easy to hit, and adds the first tests for common/crypto_utils.py and rag/utils/encrypted_storage.py.

Root cause

common/settings.py:356-369:

    # Check if encryption is enabled
    if crypto_enabled:
        try:
            from rag.utils.encrypted_storage import create_encrypted_storage

            algorithm = os.environ.get("RAGFLOW_CRYPTO_ALGORITHM", "aes-256-cbc")
            crypto_key = os.environ.get("RAGFLOW_CRYPTO_KEY")

            STORAGE_IMPL = create_encrypted_storage(storage_impl, algorithm=algorithm, key=crypto_key, encryption_enabled=crypto_enabled)
        except Exception as e:
            logging.error(f"Failed to initialize encrypted storage: {e}")
            STORAGE_IMPL = storage_impl

Any failure inside create_encrypted_storage lands in except Exception and STORAGE_IMPL becomes the raw, unencrypted impl. Measured by running that exact branch against an in-memory storage impl and storing b'PATIENT SSN 123-45-6789 CONFIDENTIAL' (RAGFLOW_CRYPTO_ENABLED=true in every row):

scenario                    wrapper                 on-disk encrypted
------------------------------------------------------------------------
KEY set, ALGORITHM default  EncryptedStorageWrapper True
KEY unset                   FakeStorage             False
KEY set, ALGORITHM typo     FakeStorage             False
KEY empty                   FakeStorage             False

Three of the four configurations that an operator can plausibly land on store the payload in plaintext. The only log line is logging.error at startup, which is easy to miss and is not repeated per write.

Why it stays invisible

CryptoUtil.decrypt() returns data that lacks the RAGF magic header unchanged (common/crypto_utils.py:99-102). That passthrough is deliberate and useful — it is what lets you enable encryption over an existing bucket — but it also means a plaintext object keeps reading back correctly after the configuration is fixed:

leaked.txt   on-disk starts with RAGF: False  reads back correctly: True
safe.txt     on-disk starts with RAGF: True   reads back correctly: True

So nothing ever surfaces the leak. There is no failed read, no exception, and no difference visible to a caller — only the bytes on disk differ. That is why this needs to fail at startup rather than degrade.

Fix

1. common/settings.py — drop the fallback. The surrounding function already fails fast for the analogous case, an unusable doc engine (raise Exception(f"Not supported doc engine: {DOC_ENGINE}"), line 325). Encryption-at-rest gets the same treatment, with a comment recording why silence is the wrong outcome here.

2. rag/utils/encrypted_storage.py — resolve the documented defaults. create_encrypted_storage(storage_impl, algorithm=None, key=None, ...) documents algorithm as "uses environment variable RAGFLOW_CRYPTO_ALGORITHM or default if None" and key as "uses environment variable RAGFLOW_CRYPTO_KEY if None". Neither was implemented — both were passed straight through to CryptoUtil:

documented default RAISES: ValueError: Unsupported algorithm: None

So the signature default was unusable and the key never fell back to the environment. Both are now resolved in the function, and explicit arguments still win over the environment. This matters for the bug above too: settings.py passes an explicit algorithm, so it never hit the None path, but any other caller relying on the documented defaults would raise — and under the old code that raise was swallowed into a plaintext fallback.

Tests

New test/unit_test/common/test_crypto_utils.py, 33 tests in four groups. Neither common/crypto_utils.py (355 lines) nor rag/utils/encrypted_storage.py had any test coverage before this.

  • TestCryptoUtil — round trip and magic header across all three supported algorithms (aes-128-cbc, aes-256-cbc, sm4-cbc), unsupported-algorithm and missing-key rejection, random IV, empty and block-aligned payloads, wrong key, deterministic key derivation, derived key length per cipher.
  • TestDecryptPassthrough — pins the magic-header passthrough as intended behaviour, since the fix above depends on it being intended.
  • TestEncryptedStorageWrapper — plaintext never reaches the backing impl, decryption on read, missing object, disabled-encryption passthrough, required-method check, and the resolved defaults.
  • TestInitSettingsCrypto — the crypto branch itself: valid config wraps, disabled leaves the impl bare, each broken config raises, and test_unencrypted_write_stays_invisible pins the leak-invisibility result above.

TestInitSettingsCrypto mirrors the RAGFLOW_CRYPTO_* branch of settings.py in a helper rather than calling init_settings(), which also connects to MySQL, Redis and the doc store. That is a deliberate trade-off and it has a consequence worth stating: test_enabled_with_broken_config_raises passes both before and after this PR, because the helper reproduces the branch without the try/except. It documents the intended contract; it does not by itself catch a regression in settings.py. The measurement in the root-cause section above, not that test, is the evidence for fix 1.

Red check — the 33 tests against the unmodified sources at 594a464:

FAILED TestEncryptedStorageWrapper::test_put_encrypts_at_rest - ValueError: Unsupported algorithm: None
FAILED TestEncryptedStorageWrapper::test_get_decrypts - ValueError: Unsupported algorithm: None
FAILED TestEncryptedStorageWrapper::test_get_missing_object_returns_none - ValueError: Unsupported algorithm: None
FAILED TestEncryptedStorageWrapper::test_disabled_encryption_stores_plaintext - ValueError: Unsupported algorithm: None
FAILED TestEncryptedStorageWrapper::test_propagates_missing_key - AssertionError: Regex pattern did not match.
FAILED TestEncryptedStorageWrapper::test_defaults_to_aes_256_cbc - ValueError: Unsupported algorithm: None
FAILED TestEncryptedStorageWrapper::test_reads_config_from_environment - ValueError: Unsupported algorithm: None
7 failed, 26 passed in 0.88s

With the fixes applied: 33 passed in 0.69s.

An autouse fixture clears RAGFLOW_CRYPTO_ENABLED / _ALGORITHM / _KEY for every test in the file, so an ambient value in a developer's shell cannot steer the results now that the environment fallback is actually read.

Verification

  • test/unit_test/common/test_crypto_utils.py — 33 passed.
  • test/unit_test/ before and after this branch: 19 failed / 324 passed → 12 failed / 331 passed, 29 skipped. The 12 remaining failures are identical before and after and are environment-only — test_time_utils.py and test_mistral_ocr_env.py, on dateutil/filelock availability and the Windows epoch.
  • ruff check and ruff format --check clean on all three files under the repo configuration.
  • All 9 lefthook file hooks pass on the staged files.

Two disclosures:

  • I could not run the full backend or Go suites locally (Windows, no MySQL/Redis/ES). Only test/unit_test/ was executed.
  • My local ruff (0.16.1) is newer than what CI pins and enables a much wider rule set, so it reports 33 pre-existing findings on these files untouched. I compared the baseline and edited findings rather than trusting the count: my change adds none and removes two (BLE001, LOG015). Under ruff's default selection plus the repo config, all three files are clean.

Note on CI

.github/workflows/tests.yml gates ragflow_preflight on the ci label, so the checks on this PR will stay idle until a maintainer applies it.

Lynn-Inf and others added 30 commits July 27, 2026 09:53
### Summary

The FunASR provider added in infiniflow#17171 defaults to a local
`http://localhost:8000/v1` server, but it still inherited the global
API-key requirement and unconditionally built an Authorization header.
This prevented the default unauthenticated self-hosted deployment from
working. The transcription path also dereferenced a missing model name
while building its multipart request.

This change:

- allows an empty API key for FunASR, matching other local providers
- omits the Authorization header when no key is configured while
preserving trimmed Bearer authentication when one is provided
- validates and trims the ASR model name before building the multipart
request, returning an error instead of panicking
- adds HTTP-level regression coverage for unauthenticated
transcription/model listing and optional authentication
…ter preview (infiniflow#17385)

## Summary

Improve the UX of the **"Delimiter for text"** field on the dataset
configuration page. The field is a single string with a backtick-based
mini-syntax, but both the tooltip and the surrounding UI failed to
surface what delimiters the backend would actually derive from a given
value — leaving users to discover by trial-and-error that the same
string produces different splits depending on file type (see infiniflow#7436,
infiniflow#4704, infiniflow#9680).
…ERN title fallback (infiniflow#17396)

## Summary

Closes two Chunker migration gaps documented in
`docs/migration_python_go_diff.md`
(diffs **2.6** and **1.7**), improving parity with the Python ingestion
pipeline.

This is the code portion of commit `261e1fd0b` on branch
`fix/batch-3-4`; the
migration document itself is tracked separately (untracked in this
commit).

### Diff 2.6 — `overlapped_percent` missing Python normalization

Python's `normalize_overlapped_percent` (`common/float_utils.py:50-58`)
accepts a
`[0,1)` fraction (the flow-canvas UI validates `[0,1)`), multiplies it
by 100,
`int()`-truncates, and clamps to `[0,90]`. Go previously only accepted a
raw
`[0,90]` percentage and **rejected** out-of-range input, so a Python
config
passing `0.1` (meaning 10%) silently produced ~0% overlap.

Added `normalizeOverlappedPercent`
(`internal/ingestion/component/chunker/common.go`) mirroring the Python
helper:

- parses numbers and numeric strings (mirrors Python `float()`; bad /
`NaN` / `Inf` → `0`),
- `0 < v < 1 → v *= 100`,
- `int()` truncation,
- clamps to `[0,90]`.

Wired into `tokenChunkerParam.Update` (`token.go`); the merge math
(`token.go:705`, `(100-x)/100`) already matched Python.
`TokenChunkerParam.Validate`
(`schema/chunker.go`) now only guards direct struct construction.

Tests: `TestNormalizeOverlappedPercent`, extended
`TestTokenChunker_NewAcceptsPythonOverlappedRange` (adds fraction/clamp
inputs),
new `TestTokenChunker_NormalizesOverlappedPercent`. The existing
reject-test cases
for `<0` / `>90` were removed because they are now normalized/clamped
(Python parity).

### Diff 1.7 — missing `BULLET_PATTERN` title-level fallback

`resolveTitleLevels` (`title.go`) now applies a 4th-level fallback: when
outline +
regex + layout all yield body level, `bulletsCategory` selects the
best-matching
bullet-pattern group (Chinese legal / numbering / Chinese numbering /
English legal
— mirroring `rag/nlp/__init__.py:258-320`) and assigns structural
levels. Guarded by
`allBodyLevel` so it never overrides an existing outline/regex level.

Tests: `TestResolveTitleLevels_BulletFallback` (4 subtests).

### Incidental test adjustments included in the commit

- `token_batch1_test.go`: overlap input changed `0.3` → `30.0` to
reflect the
  post-normalization 30% semantics.
- `real_consumer_test.go`: updated `LoadFromIngestionTask(task)` →
`LoadFromIngestionTask(ctx, task)` for the new context-first signature.

## Verification

`bash build.sh --test ./internal/ingestion/component/...` — chunker +
schema suites
pass, no regression (CGO build).

## Migration doc reference

`docs/migration_python_go_diff.md` §Chunker 1.7 and 2.6 are marked
**Fixed** for
these changes.
## Summary

- Parse chat, embedding, and rerank usage from provider responses
- Record usage with the correct model type even when no usage sink is
provided
- Cover SiliconFlow, Aliyun, Huawei Cloud, Qiniu, and VolcEngine
response formats
…7395)

### Summary

As title

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
…low#17413)

### Summary

As title, related to infiniflow#16990

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
buua436 and others added 19 commits August 3, 2026 17:46
…ush (infiniflow#17729)

## Summary

Align Go `splitOversizedUnitWith` with Python
`rag/nlp._split_oversized_unit` so the whitespace-atom sub-split
produces byte-identical chunk boundaries.

### Root cause of the divergence
cl100k token counting is **not additive across whitespace joins**
(`token(a)+token(b) != token(a+b)`). Go previously used the exact
joined-string fit check `countFn(current+atom) > budget`, while Python
accumulates a running sum `current_tokens + a_tokens > budget`. The two
formulas disagree by one atom at the boundary, so Go and Python emitted
the same chunk *count* but shifted *text*.

### Changes
- `splitOversizedUnitWith` (`token.go`): replace the exact joined-string
fit check with the running-sum check (mirroring Python's
`current_tokens` accumulator), and after a flush keep the overflow
whitespace atom (`current += atom`) instead of dropping it.
- `token_strict_cap_test.go`: relax
`TestMergeByTokenSizeFromJSON_OversizedUnitIsSubSplit` to allow the same
cl100k non-additive +1 overshoot Python exhibits (the invariant — an
oversized unit is sub-split, not collapsed — is preserved).

### Test plan
`bash build.sh --test ./internal/ingestion/component/chunker/...` —
green.

## Note
Test infrastructure for this change (golden parity harness,
`split_oversized_test.go`, `testdata/parity/**`, `known_diffs.json`,
`capture_golden.py`/`live_chunk.py`, and the `go-cmp` dependency
promotion) is split into a separate, stacked PR infiniflow#17735 so this PR stays
minimal (production code only).

This PR is **independent of infiniflow#17712** (the offline BPE loader). It is
based on `upstream/main` and contains only this change; no BPE-loader
code is included.

Co-authored-by: CodeBuddy <[email protected]>
…nfiniflow#17699)

## Summary

Relate to infiniflow#17284

Migrate 10 OpenAI-compatible drivers (`orcarouter`, `perplexity`,
`ppio`, `qiniu`, `ragcon`, `stepfun`, `togetherai`, `tokenhub`,
`tokenpony`, `upstage`) to use the unified response handlers
(`HandleNonStreamingResponse` / `HandleStreamingResponse`), following
the same pattern established by `deepseek` in infiniflow#17634.

- Cut ~150 lines per driver (1436 lines removed, 62 added across 10
files).
- No functional changes — pure deduplication of HTTP plumbing.
- Each driver now routes through `baseModel.doRequest()` and
`HandleNonStreamingResponse()`.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
…lently offline (infiniflow#17712)

## Summary

RAGFlow's Go tokenizer silently returned **0 tokens for every string**
whenever the `cl100k_base` BPE table could not be loaded — which is the
normal case for an offline/air-gapped Go server. This PR makes the
loader resolve the table from disk (where RAGFlow actually ships it) and
fail loudly when it is genuinely missing.

## Root cause

`tiktoken-go`'s stock loader downloads the encoding table over HTTP and
caches it under `TIKTOKEN_CACHE_DIR`. That does not work for RAGFlow:

- `TIKTOKEN_CACHE_DIR` is exported **only inside the Python process**
(`common/token_utils.py`). `docker/entrypoint.sh` launches the Go binary
(`bin/ragflow_server`) from a shell, so the Go process never inherits
the variable.
- The Dockerfile *does* ship the table (under its sha1 name in the
working directory), but nothing told the Go side to look there.
- Reaching `openaipublic.blob.core.windows.net` at runtime is not an
option for air-gapped installs, and is unreliable where that host is
blocked.

The failure was **silent**: `NumTokensFromString` returns `0` when the
encoder fails to build, and a `sync.Once` memoizes that error for the
process lifetime. Every token count became `0`, so chunk merging never
crossed its token budget and an entire document collapsed into a single
chunk. Python has no such failure mode because its encoder is built at
import time (a missing table aborts startup instead of degrading).

## Fix

Register a local-only `BpeLoader` via `tiktoken.SetBpeLoader`
(`internal/tokenizer/bpe_loader.go`) that resolves the table from disk
**only**, in priority order:

1. `TIKTOKEN_CACHE_DIR` / `DATA_GYM_CACHE_DIR` (honored so operators who
already configured one keep working).
2. The working directory, the executable's directory, and all of their
ancestors — matching the Dockerfile layout (table under its sha1 name in
the install root).
3. A `ragflow_deps/<basename>` checkout produced by
`ragflow_deps/download_deps.py`.

It **never performs network I/O**. When nothing is found it returns an
error listing every path it tried (pointing at `download_deps.py` or
`TIKTOKEN_CACHE_DIR`), so a genuinely missing table fails loudly instead
of degrading to zero.

## Test plan

- `internal/tokenizer/bpe_loader_test.go` (unit tier, runs under `bash
build.sh --test ./internal/tokenizer/...`):
- Loader reads from `TIKTOKEN_CACHE_DIR`, `DATA_GYM_CACHE_DIR`, the
sha1-named file in the working dir, and the bundled `ragflow_deps/`
name.
  - Explicit cache dir wins over the bundled vocab.
  - A malformed table is reported as an error rather than skipped.
- A genuinely missing table reports the candidates it tried (no network
attempt).
- `NumTokensFromString` matches Python-derived anchors (`""`→0,
`"hello"`→1, `"hello world"`→2, `"hello, world!"`→4, `"世界"`→3, `"Hello
世界 🌍"`→8, `"RAGFlow"`→3).

## Notes

- `.github/workflows/tests.yml` currently excludes `internal/tokenizer`
from `go test`, so these tests do not run in CI. The tokenizer fix is
exercised in CI indirectly via the chunker package once a
token-count-sensitive parity case lands (tracked separately). Consider
including `internal/tokenizer` in CI as a follow-up.
- Supported deployments already ship the table (`download_deps.py` →
`ragflow_deps/cl100k_base.tiktoken`; Dockerfile → `<sha1>` in cwd), so
no `ENV` change is required for the fix to take effect. Setting `ENV
TIKTOKEN_CACHE_DIR` in the Dockerfile remains a cheap
belt-and-suspenders hardening that can be done separately.

🤖 Generated with [CodeBuddy Code](https://cnb.cool/codebuddy)

---------

Co-authored-by: CodeBuddy <[email protected]>
Co-authored-by: CodeBuddy Code <[email protected]>
Co-authored-by: CodeBuddy <[email protected]>
…nfiniflow#17700)

## Summary

Relate to infiniflow#17284. Completes the batch 5 migration of 7 OpenAI-compatible
drivers (`vllm`, `volcengine`, `xai`, `xiaomi`, `xinference`, `xunfei`,
`zhipu-ai`) onto the unified request/response helpers
(`doRequest`/`doStreamRequest` +
`HandleNonStreamingResponse`/`HandleStreamingResponse` +
`ParserConfig`), established by `deepseek` in infiniflow#17634.

This branch is rebased on the current `pr/migrate-models-batch5` and
fixes the issues in the previous state of the PR.

Co-authored-by: Haruko386 <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
…m flush (infiniflow#17740)

## Summary

Adds a self-contained regression guard for `splitOversizedUnitWith`
after PR infiniflow#17729
aligned it with Python's `rag/nlp._split_oversized_unit` running-sum
flush.

infiniflow#17729 shipped a `slack=1` relaxation in `token_strict_cap_test.go` (the
oversized
unit is now sub-split with the same running-sum flush Python uses, which
can leave a
piece one token over the nominal budget due to cl100k non-additivity).
This PR adds
the missing positive proof that the sub-split boundaries are correct, so
the relaxed
assertion is no longer unguarded.

## Changes

- `split_oversized_guard_test.go` (new, self-contained — no harness
loader, no
  `testdata`; the Python oracle is inlined):
- `TestSplitOversizedUnitRunningSumMatchesPython`: asserts the exact
piece
boundaries (live tokenizer) match Python's `_split_oversized_unit`,
compensating
    the `slack=1` relaxation from infiniflow#17729.
- `TestSplitOversizedUnitDeadTokenizerCollapses`: asserts a
zero-counting tokenizer
collapses the B1 paragraph into exactly one chunk, catching a silently
dead encoder
    that a non-empty-result check would miss.

## Notes

- Test function names are deliberately distinct from PR infiniflow#17735's
`TestSplitOversizedUnitMatchesPython`, so the two PRs verify
independently and do not
  conflict at merge time.
- PR infiniflow#17735 (golden parity harness) is intentionally left unchanged per
the split plan.

## Test plan

`bash build.sh --test ./internal/ingestion/component/chunker/` — green,
including both
new tests.

Co-authored-by: CodeBuddy <[email protected]>
…hole (infiniflow#17739)

Fixes two TokenChunker **json-path** over-segmentation bugs that diverge
from Python's `rag/app` chunkers (tracked as `go_bug` known-diffs).
GO CLI: add enterprise empty Dao files
…ig is broken

With RAGFLOW_CRYPTO_ENABLED=true, init_settings() caught any error from
create_encrypted_storage(), logged it, and assigned the unencrypted storage
impl to STORAGE_IMPL. The server then started normally and wrote every
document to object storage in the clear -- the exact opposite of what the
operator asked for, behind a single log line.

Three one-character mistakes in docker/.env trigger it, and all three leave
documents unencrypted on disk: the RAGFLOW_CRYPTO_KEY line left commented
out, an empty key, and a typo in RAGFLOW_CRYPTO_ALGORITHM ("aes256-cbc").

Nothing surfaces the leak afterwards. BaseCrypto.decrypt() returns data
without the "RAGF" magic header unchanged -- deliberate, so encryption can be
enabled over an existing bucket -- so a plaintext object still reads back
correctly even after the configuration is fixed. There is no health check or
metric that distinguishes "encrypting" from "silently not encrypting".

Drop the fallback so a broken crypto config aborts startup, matching the
unsupported-doc-engine branch a few lines above. Failing to start is loud and
recoverable; silently storing unencrypted documents is neither.

Also resolve the defaults create_encrypted_storage already documents. Passing
algorithm=None straight to CryptoUtil raised "Unsupported algorithm: None",
so the default in its own signature was unusable, and the RAGFLOW_CRYPTO_KEY
fallback promised by both docstrings (and by CryptoUtil's error message) was
never actually read. Explicit arguments still win.

common/crypto_utils.py and rag/utils/encrypted_storage.py had no tests. Adds
33 covering round-trips for all three algorithms, the magic header, rejection
of a bad algorithm or missing key, random IVs, empty and block-aligned
payloads, wrong-key behavior, derived key lengths, the decrypt() passthrough,
the storage wrapper, the resolved defaults, and the init_settings crypto
branch -- including a test pinning why the fallback had to go. Seven fail
before this change.

Fixes infiniflow#17752
@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Aug 3, 2026
@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9a8fd5c1-6183-44fd-a418-9d75a9a94e6d

📥 Commits

Reviewing files that changed from the base of the PR and between 639c4a7 and 5568c10.

📒 Files selected for processing (2)
  • rag/utils/encrypted_storage.py
  • test/unit_test/common/test_crypto_utils.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • test/unit_test/common/test_crypto_utils.py
  • rag/utils/encrypted_storage.py

📝 Walkthrough

Walkthrough

Encrypted storage now reads missing configuration from environment variables and defaults the algorithm to aes-256-cbc. Enabled encryption errors propagate during settings initialization instead of selecting plaintext storage. Tests cover crypto behavior, storage wrapping, configuration, and legacy plaintext reads.

Changes

Encrypted storage behavior

Layer / File(s) Summary
Crypto configuration and storage wrapper
rag/utils/encrypted_storage.py, test/unit_test/common/test_crypto_utils.py
create_encrypted_storage resolves unset values from environment variables. Tests cover cipher behavior, key handling, plaintext passthrough, wrapper operations, and argument precedence.
Settings initialization and failure propagation
common/settings.py, test/unit_test/common/test_crypto_utils.py
Encrypted storage initialization no longer falls back to plaintext storage when configuration or creation fails. Tests cover enabled and disabled modes, invalid configuration, and reading previously unencrypted objects.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related issues

  • infiniflow/ragflow#17752 — Directly matches the removal of silent plaintext fallback and the encrypted-storage default resolution changes.

Poem

I’m a rabbit guarding each key,
No quiet fallback hides what should be seen.
Environment winds set cipher ways,
Tests hop through encrypted days.
Plaintext elders still pass through—
Secure new writes now greet the dew.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states the primary change: fail fast when broken crypto configuration would otherwise cause plaintext storage.
Description check ✅ Passed The description includes the required Summary section and provides clear background, root cause, implementation details, tests, and verification results.
Docstring Coverage ✅ Passed Docstring coverage is 80.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@common/settings.py`:
- Around line 365-370: Update the encrypted-storage initialization flow around
create_encrypted_storage to log the selected algorithm immediately before
construction and validation. Use the existing logging facility, include
algorithm in the message, and never include crypto_key or its value in the log.

In `@rag/utils/encrypted_storage.py`:
- Around line 263-267: Update the argument resolution in
create_encrypted_storage so environment fallbacks apply only when algorithm or
key is None, preserving explicit empty strings for validation and rejection. Add
regression tests with valid ambient RAGFLOW_CRYPTO_ALGORITHM and
RAGFLOW_CRYPTO_KEY values that pass empty algorithm and key arguments and verify
they are not replaced by the environment.

In `@test/unit_test/common/test_crypto_utils.py`:
- Around line 241-263: The tests currently duplicate the crypto
storage-selection logic instead of exercising the settings implementation.
Extract the RAGFLOW_CRYPTO_* selection block from init_settings into a private
helper in common/settings.py, invoke that helper from init_settings, and update
the tests to call it with FakeStorage and mocked dependencies; remove
_init_storage from test_crypto_utils.py.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 65211705-00a3-412c-9c87-e3f949d4fa2e

📥 Commits

Reviewing files that changed from the base of the PR and between 594a464 and 639c4a7.

📒 Files selected for processing (3)
  • common/settings.py
  • rag/utils/encrypted_storage.py
  • test/unit_test/common/test_crypto_utils.py

Comment thread common/settings.py
Comment on lines +365 to +370
from rag.utils.encrypted_storage import create_encrypted_storage

algorithm = os.environ.get("RAGFLOW_CRYPTO_ALGORITHM", "aes-256-cbc")
crypto_key = os.environ.get("RAGFLOW_CRYPTO_KEY")

STORAGE_IMPL = create_encrypted_storage(storage_impl, algorithm=algorithm, key=crypto_key, encryption_enabled=crypto_enabled)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Log encrypted-storage initialization before validation.

The new fail-fast path has no log before create_encrypted_storage validates the configuration. Log the selected algorithm before construction. Do not log crypto_key.

Proposed fix
         algorithm = os.environ.get("RAGFLOW_CRYPTO_ALGORITHM", "aes-256-cbc")
         crypto_key = os.environ.get("RAGFLOW_CRYPTO_KEY")
+        logging.info("Initializing encrypted storage with algorithm: %s", algorithm)
 
         STORAGE_IMPL = create_encrypted_storage(storage_impl, algorithm=algorithm, key=crypto_key, encryption_enabled=crypto_enabled)

As per coding guidelines, “**/*.py: Add logging for new flows.”

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
from rag.utils.encrypted_storage import create_encrypted_storage
algorithm = os.environ.get("RAGFLOW_CRYPTO_ALGORITHM", "aes-256-cbc")
crypto_key = os.environ.get("RAGFLOW_CRYPTO_KEY")
STORAGE_IMPL = create_encrypted_storage(storage_impl, algorithm=algorithm, key=crypto_key, encryption_enabled=crypto_enabled)
from rag.utils.encrypted_storage import create_encrypted_storage
algorithm = os.environ.get("RAGFLOW_CRYPTO_ALGORITHM", "aes-256-cbc")
crypto_key = os.environ.get("RAGFLOW_CRYPTO_KEY")
logging.info("Initializing encrypted storage with algorithm: %s", algorithm)
STORAGE_IMPL = create_encrypted_storage(storage_impl, algorithm=algorithm, key=crypto_key, encryption_enabled=crypto_enabled)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@common/settings.py` around lines 365 - 370, Update the encrypted-storage
initialization flow around create_encrypted_storage to log the selected
algorithm immediately before construction and validation. Use the existing
logging facility, include algorithm in the message, and never include crypto_key
or its value in the log.

Source: Coding guidelines

Comment thread rag/utils/encrypted_storage.py Resolved
Comment on lines +241 to +263
def _init_storage(monkeypatch, env):
"""Run the RAGFLOW_CRYPTO_* branch of init_settings against a fake impl.

Mirrors common/settings.py rather than calling init_settings(), which
also connects to MySQL, Redis and the doc store.
"""
import os

for name in ("RAGFLOW_CRYPTO_ENABLED", "RAGFLOW_CRYPTO_ALGORITHM", "RAGFLOW_CRYPTO_KEY"):
monkeypatch.delenv(name, raising=False)
for name, value in env.items():
monkeypatch.setenv(name, value)

storage_impl = FakeStorage()
if os.environ.get("RAGFLOW_CRYPTO_ENABLED", "false").lower() != "true":
return storage_impl

return create_encrypted_storage(
storage_impl,
algorithm=os.environ.get("RAGFLOW_CRYPTO_ALGORITHM", "aes-256-cbc"),
key=os.environ.get("RAGFLOW_CRYPTO_KEY"),
encryption_enabled=True,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Test the settings-owned storage selection path.

_init_storage duplicates the crypto branch instead of invoking common/settings.py. These tests still pass if init_settings restores the plaintext fallback that this PR removes.

Extract the storage-selection block to a private helper in common/settings.py. Call that helper from init_settings. Test the helper with FakeStorage and mocked dependencies. Remove this test-only implementation.

As per coding guidelines, “center refactors on the owning abstraction” and “collapse duplicate implementations.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/unit_test/common/test_crypto_utils.py` around lines 241 - 263, The tests
currently duplicate the crypto storage-selection logic instead of exercising the
settings implementation. Extract the RAGFLOW_CRYPTO_* selection block from
init_settings into a private helper in common/settings.py, invoke that helper
from init_settings, and update the tests to call it with FakeStorage and mocked
dependencies; remove _init_storage from test_crypto_utils.py.

Source: Coding guidelines

…nt is None

An explicitly empty algorithm or key is a broken value, not a request for
the ambient environment. Falling back would encrypt with a key the caller
never asked for and could not observe.
@LHMQ878

LHMQ878 commented Aug 3, 2026

Copy link
Copy Markdown
Author

Thanks — I probed all three before acting. One is a real bug and is now fixed; the other two I'd push back on.

2 — explicit empty values (valid, fixed in 5568c10)

Confirmed by measurement. With RAGFLOW_CRYPTO_KEY set in the environment, key="" produced the same derived key as key=None:

env RAGFLOW_CRYPTO_KEY = '0123456789abcdef0123456789abcdef'
  key=None (documented fallback)   -> OK  key=b'V\xd53R\xf0\xe5\x01\xb0...'
  key="" (explicit empty)          -> OK  key=b'V\xd53R\xf0\xe5\x01\xb0...'   <- identical
  key='ZZZZ...' (explicit)         -> OK  key=b'x\xed\x1e&\xa1e\xdaH...'

Fixed as you suggested, guarding on is None:

if algorithm is None:
    algorithm = os.environ.get("RAGFLOW_CRYPTO_ALGORITHM", "aes-256-cbc")
if key is None:
    key = os.environ.get("RAGFLOW_CRYPTO_KEY")

Two regression tests added, and A/B'd so they aren't vacuous — 2 failed against the old or version, 35 passed with the fix.

One correction to the severity, though: this is not reachable from the production path, so it isn't a live plaintext/wrong-key risk today. common/settings.py reads the same variable it passes, so argument and environment can never disagree:

RAGFLOW_CRYPTO_KEY=''                                -> ValueError: Encryption key not provided
RAGFLOW_CRYPTO_KEY='0123...abcdef'                   -> constructed OK

CryptoUtil.__init__ already does if not key: raise, which treats "" and None alike. So the empty-env case this PR is about was already failing fast correctly. Worth fixing anyway since create_encrypted_storage is public and the contract should hold for any caller — just not a Major security hole in the shipped code.

1 — log before validation (declining)

The log would sit one line above create_encrypted_storage, which already logs "Encryption enabled in storage wrapper" on success and raises with the algorithm name on failure (Unsupported algorithm: bogus). Adding a third message in between logs an intent that the very next line may invalidate — and on the failure path it means the last thing in the log is a success-shaped line, which is the opposite of what this PR is for. The guideline is "add logging for new flows"; this flow is logged at both outcomes.

3 — extract a helper from init_settings (declining, but the concern is fair)

You're right that _init_storage duplicating the branch means the test would still pass if someone restored the plaintext fallback. But extracting a private helper from init_settings is a refactor of a function that also wires MySQL, Redis and the doc store — out of scope for a fix PR, and it would make this diff much harder for a maintainer to review against the security claim.

Happy to do it as a follow-up if a maintainer wants it. If the duplication risk is the blocker, a cheaper option is asserting the source of common/settings.py contains no STORAGE_IMPL = storage_impl inside the crypto branch — ugly, but it actually pins the thing at risk. Let me know which you'd prefer.

@JinHai-CN

Copy link
Copy Markdown
Member

@yngvarhuang, You can also review this one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: RAGFLOW_CRYPTO_ENABLED=true silently falls back to unencrypted storage when the crypto config is broken