Repository navigation
Conversation
### 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
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
…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).
Signed-off-by: Jin Hai <[email protected]>
…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.
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
## 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
…nce-specific values (infiniflow#17422)
Introduced oxfmt
Signed-off-by: Jin Hai <[email protected]>
…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>
…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]>
…iflow#17728) ### Summary As title now can edit
### Summary As title:
### Summary As title
…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]>
Signed-off-by: Jin Hai <[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
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughEncrypted storage now reads missing configuration from environment variables and defaults the algorithm to ChangesEncrypted storage behavior
Estimated code review effort: 3 (Moderate) | ~20 minutes Possibly related issues
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
common/settings.pyrag/utils/encrypted_storage.pytest/unit_test/common/test_crypto_utils.py
| 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) |
There was a problem hiding this comment.
📐 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.
| 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
| 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, | ||
| ) |
There was a problem hiding this comment.
🔒 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.
|
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
|
|
@yngvarhuang, You can also review this one. |
Summary
Fixes #17752.
RAGFLOW_CRYPTO_ENABLED=trueis 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 increate_encrypted_storagethat made the broken-config case easy to hit, and adds the first tests forcommon/crypto_utils.pyandrag/utils/encrypted_storage.py.Root cause
common/settings.py:356-369:Any failure inside
create_encrypted_storagelands inexcept ExceptionandSTORAGE_IMPLbecomes the raw, unencrypted impl. Measured by running that exact branch against an in-memory storage impl and storingb'PATIENT SSN 123-45-6789 CONFIDENTIAL'(RAGFLOW_CRYPTO_ENABLED=truein every row):Three of the four configurations that an operator can plausibly land on store the payload in plaintext. The only log line is
logging.errorat startup, which is easy to miss and is not repeated per write.Why it stays invisible
CryptoUtil.decrypt()returns data that lacks theRAGFmagic 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: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, ...)documentsalgorithmas "uses environment variable RAGFLOW_CRYPTO_ALGORITHM or default if None" andkeyas "uses environment variable RAGFLOW_CRYPTO_KEY if None". Neither was implemented — both were passed straight through toCryptoUtil: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.pypasses an explicit algorithm, so it never hit theNonepath, 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. Neithercommon/crypto_utils.py(355 lines) norrag/utils/encrypted_storage.pyhad 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, andtest_unencrypted_write_stays_invisiblepins the leak-invisibility result above.TestInitSettingsCryptomirrors theRAGFLOW_CRYPTO_*branch ofsettings.pyin a helper rather than callinginit_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_raisespasses both before and after this PR, because the helper reproduces the branch without thetry/except. It documents the intended contract; it does not by itself catch a regression insettings.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:
With the fixes applied:
33 passed in 0.69s.An autouse fixture clears
RAGFLOW_CRYPTO_ENABLED/_ALGORITHM/_KEYfor 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.pyandtest_mistral_ocr_env.py, ondateutil/filelockavailability and the Windows epoch.ruff checkandruff format --checkclean on all three files under the repo configuration.lefthookfile hooks pass on the staged files.Two disclosures:
test/unit_test/was executed.BLE001,LOG015). Under ruff's default selection plus the repo config, all three files are clean.Note on CI
.github/workflows/tests.ymlgatesragflow_preflighton thecilabel, so the checks on this PR will stay idle until a maintainer applies it.