Repository navigation
Run the malware gate on the RAG embedding model before it loads - #6887
Conversation
Setting the RAG embedding model through PUT /api/settings/embedding-model persisted an arbitrary repo and later handed it straight to SentenceTransformer, which deserializes pickle weights. Unlike the normal model-load paths, this route never ran evaluate_file_security, and force skipped verification entirely, so a repo Hugging Face flags as unsafe (or any repo under force) could be downloaded and loaded in the backend process without a scan. Run the malware/pickle scan at both ends: the settings endpoint now scans before persisting and returns 409 on a flagged repo even under force (force still only skips the is-embedding-model type check for offline or local repos), and the embedder scans again at the load sink so a name that arrives via env or default is covered too. Local paths and unreachable scans fail open inside evaluate_file_security, and the sink never bricks the embedder on a gate error.
|
@codex review |
There was a problem hiding this comment.
Code Review
This pull request introduces a security gate for RAG embedding models to prevent loading or persisting models flagged as unsafe by Hugging Face's security scan. It adds a security guard check before loading models via SentenceTransformer, integrates this check into the settings route, and includes comprehensive tests to verify the behavior. The review feedback highlights two critical security bypass vulnerabilities where gated or private models could fail open because the Hugging Face token (hf_token) is not passed or resolved from the environment. Actionable suggestions are provided to fall back to os.environ.get("HF_TOKEN") in both the model loading guard and the settings route.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| try: | ||
| from utils.security import evaluate_file_security, security_load_subdirs | ||
| blocked = evaluate_file_security(name, load_subdirs = security_load_subdirs(name)).blocked | ||
| except Exception: | ||
| return | ||
| if blocked: |
There was a problem hiding this comment.
The load-sink security check _guard_model_security does not pass the Hugging Face token (hf_token) to evaluate_file_security or security_load_subdirs. Because evaluate_file_security explicitly disables token fallback (passing token = False to hf_model_info) when hf_token is None, any gated or private embedding model will fail to have its security status fetched and will fail open (bypassing the security gate).
To prevent this security bypass, retrieve the Hugging Face token from the environment (os.environ.get("HF_TOKEN")) and pass it to both evaluate_file_security and security_load_subdirs.
| try: | |
| from utils.security import evaluate_file_security, security_load_subdirs | |
| blocked = evaluate_file_security(name, load_subdirs = security_load_subdirs(name)).blocked | |
| except Exception: | |
| return | |
| if blocked: | |
| try: | |
| import os | |
| from utils.security import evaluate_file_security, security_load_subdirs | |
| token = os.environ.get("HF_TOKEN") or None | |
| blocked = evaluate_file_security( | |
| name, hf_token = token, load_subdirs = security_load_subdirs(name, token) | |
| ).blocked |
There was a problem hiding this comment.
Fixed in 0644f66: the sink threads the ambient loader token into evaluate_file_security and security_load_subdirs. Test added.
| event = "settings.update_embedding_model_failed", | ||
| log = logger, | ||
| ) from exc | ||
| hf_token = (payload.hf_token or "").strip() or None |
There was a problem hiding this comment.
If the API payload does not contain a Hugging Face token, hf_token defaults to None. Since evaluate_file_security explicitly disables token fallback when hf_token is None, any gated or private embedding model configured via environment variables or defaults will fail to have its security status fetched and will fail open.
To ensure robust security verification, fall back to the environment's HF_TOKEN if the payload does not provide one.
| hf_token = (payload.hf_token or "").strip() or None | |
| import os | |
| hf_token = (payload.hf_token or "").strip() or os.environ.get("HF_TOKEN") or None |
There was a problem hiding this comment.
Fixed in 0644f66: the settings scan falls back to the loader token (scan_token = hf_token or _ambient_hf_token()) when the payload omits one.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a78b979046
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| """ | ||
| try: | ||
| from utils.security import evaluate_file_security, security_load_subdirs | ||
| blocked = evaluate_file_security(name, load_subdirs = security_load_subdirs(name)).blocked |
There was a problem hiding this comment.
Pass the load token into the sink scan
When the embedding model comes from RAG_EMBEDDING_MODEL/the default path and is a gated or private repo accessible through HF_TOKEN, this sink guard runs the Hub security lookup without any token. evaluate_file_security then calls the Hub with token=False when hf_token is omitted, so the scan fails open for the exact repo that SentenceTransformer can still download using the process Hugging Face credentials. That leaves env-configured private embedding models unscanned at the load sink; thread the same token source used for the actual load (for example HF_TOKEN) into both security_load_subdirs and evaluate_file_security.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 0644f66: the sink now resolves the loader token (HF_TOKEN env or the cached login) via huggingface_hub.get_token() and passes it to both the scan and security_load_subdirs, so a gated repo is scanned rather than failing open. Test added.
|
|
||
| device = _device() | ||
| logger.info("loading embedding model %s on %s", name, device) | ||
| _guard_model_security(name) |
There was a problem hiding this comment.
Keep malware blocks out of the ST fallback path
When this guard raises during the initial ST warmup or after a settings-driven model change, the surrounding broad except Exception paths (_build_st_backend_or_fallback() and _SentenceTransformersBackend.encode()) treat it like a normal ST/CUDA failure and switch to the llama-server fallback whenever that binary is present. In those environments a flagged embedding repo is not surfaced as the intended hard malware block; the process silently changes backends (or later fails with a GGUF-resolution error). Use an exception type or control flow that the fallback handlers do not swallow for security decisions.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 0644f66: the block now raises a distinct UnsafeEmbeddingModelError that both the encode() and _build_st_backend_or_fallback() handlers re-raise, so a flagged model hard-fails instead of silently switching to the llama-server backend. Test added.
| if evaluate_file_security( | ||
| model, hf_token = hf_token, load_subdirs = security_load_subdirs(model, hf_token) |
There was a problem hiding this comment.
Scope GGUF scans to files the backend loads
When this install is using the llama-server embedding backend and the user saves a remote GGUF embedder (or a model whose -GGUF companion is what will load), this scan still evaluates the repo as if SentenceTransformer will deserialize root pickle weights. The actual llama-server resolver only lists and downloads non-mmproj .gguf files (core/rag/embed_llama_server.py lines 171-177), so a mixed repo with a flagged root pytorch_model.bin is rejected even though that file is not on the load path. Skip or scope the malware check for remote GGUF loads the same way the local GGUF path is skipped.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This one does not hold: evaluate_file_security already treats .gguf and .safetensors as inert and only blocks a root-level pickle load vector, so a pure-GGUF llama-server embedder is never over-blocked. Scanning still runs so a GGUF repo that also ships a malicious root pickle is caught, which is the intended defense in depth.
There was a problem hiding this comment.
Revisiting this: my earlier reply was too narrow. The companion-repo over-block is genuine, not just the pure-gguf case. Fixed in cf78a38 by scoping the ST pickle scan to the sentence-transformers backend, so it is skipped whenever the llama-server backend is active. On that path the embedder loads only non-mmproj .gguf files (inert) from the -GGUF companion, so a mixed repo with a flagged root pytorch_model.bin and a clean GGUF companion is no longer rejected. The GGUF availability checks cover the llama path instead.
The load-sink scan ran without a token, so evaluate_file_security (which passes token=False when none is given) could not reach a gated or private repo and failed open for exactly the model SentenceTransformer would still load. Resolve the loader's own token (HF_TOKEN env or the cached login) and pass it to the sink scan, and fall back to it in the settings endpoint when the request omits one. The sink previously raised a plain RuntimeError, which the llama-server fallback in encode() and _build_st_backend_or_fallback() swallowed as a routine ST failure, silently switching backends instead of blocking. Raise a distinct UnsafeEmbeddingModelError that both fallback paths re-raise, so a flagged model hard-fails.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0644f6645f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| ): | ||
| hf_token = (payload.hf_token or "").strip() or None | ||
| is_local_gguf = _llama_backend_active() and _resolves_as_local_gguf(model) | ||
| if model != default_embedding_model() and not is_local_gguf: |
There was a problem hiding this comment.
Gate only the repo the active embedder loads
When RAG_EMBED_BACKEND resolves to llama-server (the CPU/macOS auto path), this condition still runs the SentenceTransformer pickle gate on model, but LlamaServerBackend._resolve_model_path() loads config.effective_gguf_repo() first (usually <model>-GGUF) and only falls back to model. A custom ST repo with an HF-flagged pickle but a clean GGUF companion is now rejected before the GGUF availability check, and force cannot bypass it, even though the unsafe pickle is never downloaded or deserialized by the GGUF backend. Please skip this gate for the llama-server path or apply checks to the actual backend load candidates.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Agreed, fixed in cf78a38. The ST pickle scan now only runs when the sentence-transformers backend is the active embedder, i.e. it is skipped when _llama_backend_active() is true. On the llama-server path the embedder loads GGUF files (inert) from the -GGUF companion repo and never deserializes the ST repo's pickle, so a custom ST repo with a flagged pickle and a clean GGUF companion is no longer rejected here. The existing GGUF availability checks (gguf_named / _local_gguf_backend_error / _hf_gguf_backend_error) still cover the llama path.
|
|
||
| token = _ambient_hf_token() | ||
| blocked = evaluate_file_security( | ||
| name, hf_token = token, load_subdirs = security_load_subdirs(name, token) |
There was a problem hiding this comment.
Include SentenceTransformer module subdirs in the scan
For SentenceTransformer repos that load weights from module directories such as 0_Transformer/ (the repo already recognizes modules.json as the local embedding-model marker), passing only security_load_subdirs() leaves those module roots out of the scan scope. evaluate_file_security treats a flagged 0_Transformer/pytorch_model.bin as a nested shard and allows it when no root index references it, so a malicious embedding repo can pass both this sink guard and the settings guard and then still be deserialized by SentenceTransformer(...).
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch, fixed in cf78a38. I now read the module dirs from the repo modules.json (each module 's non-empty "path", e.g. 0_Transformer/) and pass them as load roots to evaluate_file_security at both the settings endpoint and the load sink, unioned with security_load_subdirs. So a flagged pickle directly under a module dir is treated as root-level there and blocks instead of passing as an unreferenced nested shard. The new _st_module_subdirs helper reads modules.json via huggingface_hub for a remote repo or from disk for a local path, and swallows every failure to () so it never bricks the embedder.
| model, hf_token = scan_token, load_subdirs = security_load_subdirs(model, scan_token) | ||
| ).blocked: | ||
| raise HTTPException( | ||
| status_code = 409, |
There was a problem hiding this comment.
Avoid returning the forceable status for hard blocks
The settings frontend treats every 409 from /api/settings/embedding-model as a verification failure that can be retried with force (see EmbeddingModelVerificationError and embeddingModelNeedsForce), but this new malware block is intentionally not forceable and returns the same 409 even when force=true. When a repo is actually flagged, users are shown a “Save anyway” action that can never succeed; return a distinct status/error kind or update the client contract so hard security blocks do not enter the force flow.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right, fixed in cf78a38. The hard security block now returns 403 instead of 409. The settings client routes every 409 into the forceable "save anyway" flow (EmbeddingModelVerificationError -> embeddingModelNeedsForce), but this block cannot be bypassed by force, so 403 is a distinct status the client treats as non-forceable. On the frontend I added an EmbeddingModelBlockedError for the 403 and the save handler keeps the "save anyway" action hidden for it. The block itself is unchanged and still blocks under force.
… gate to the ST backend Extend the RAG embedding malware gate so a poisoned pickle under a SentenceTransformer module dir (for example 0_Transformer/pytorch_model.bin) blocks. Those dirs are read from the repo's modules.json and passed as load roots to evaluate_file_security at both the settings endpoint and the load sink, so such a pickle is treated as root-level there instead of an unreferenced nested shard that was previously allowed. Scope the ST pickle scan to the sentence-transformers backend. On the llama-server backend the embedder loads GGUF files (inert) from the -GGUF companion repo, never the ST repo's pickle, so a custom ST repo with a flagged pickle and a clean GGUF companion is no longer rejected. The existing GGUF availability checks already cover that path. Return 403 for the hard security block instead of 409. The settings UI routes every 409 into the forceable save-anyway flow, but this block cannot be bypassed by force, so it now uses a distinct status the client treats as non-forceable.
|
@codex review |
|
@codex review |
3 similar comments
|
@codex review |
|
@codex review |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b5c74173d3
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| scan_st_pickle = ( | ||
| model != default_embedding_model() and not is_local_gguf and not _llama_backend_active() | ||
| ) |
There was a problem hiding this comment.
Honor the active llama fallback before scanning ST pickles
When auto initially resolves to sentence-transformers on a GPU but _build_st_backend_or_fallback() has already swapped the process to LlamaServerBackend after an ST load failure, _llama_backend_active() still recomputes from hardware and returns false. In that state the active embedder will load the GGUF companion, but this branch still scans and 403s the ST repo's flagged pickle even under force, rejecting models the current backend could safely use; account for the cached llama fallback before enabling the ST pickle scan.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The authoritative pre-load gate is _guard_model_security in core/rag/embeddings.py, which every ST load path funnels through via _get. This save-time scan only ever over-blocks here (fails safe): _get_backend has no ST fallback when a llama alias is active, so the divergence can never skip a scan that a real ST load needs. Leaving as is.
|
|
||
| # Fall back to the loader's own token so a gated/private repo is actually scanned | ||
| # (a token-less scan fails open for exactly the repo that would still load). | ||
| scan_token = hf_token or _ambient_hf_token() |
There was a problem hiding this comment.
Fall back when the supplied scan token is unusable
When the UI sends any non-empty HF token, this selects it and never tries the loader's ambient token. If that token is stale or lacks access while force=true, evaluate_file_security sees the scan as unavailable and fails open, so a repo that the backend could scan with its own HF_TOKEN/cached login is persisted and only rejected later at load time. Retry with the ambient token (or no token for public repos) before allowing a forced save.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The security guarantee is enforced at load time by _guard_model_security using the ambient token, which is the same token SentenceTransformer uses to download. If the ambient token can fetch the repo, the load-time scan blocks the flagged pickle before construction; if it cannot, the download itself fails and nothing deserializes. This save-time scan is an early UX signal that fails open when unreachable by design (settings.py:401-402), so there is no unsafe load path.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b5c74173d3
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| scan_st_pickle = ( | ||
| model != default_embedding_model() and not is_local_gguf and not _llama_backend_active() | ||
| ) |
There was a problem hiding this comment.
Base the pickle scan on the actual backend
When auto resolves to sentence-transformers (for example because a GPU is present) but the warm probe has already fallen back to LlamaServerBackend after an ST/torch load failure in core/rag/embeddings.py::_build_st_backend_or_fallback, _llama_backend_active() still re-runs _resolve_auto() and returns false instead of reflecting the cached fallback backend. In that state the process will load only GGUF, but this condition still hard-blocks a repo whose ST pickle is flagged even if its GGUF companion is clean, which is the false rejection the surrounding comment says to avoid. Consider deciding scan_st_pickle from the actual cached backend/fallback, or from an explicit ST backend selection, rather than only the auto resolver.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 17c956f: the scan now bases the decision on the actual backend via embeddings.active_backend_is_llama(), which returns true when the cached backend is a LlamaServerBackend (including a runtime fallback from sentence-transformers), and defers to the resolver only before a backend is built. So after a fallback the ST pickle gate is skipped and a flagged-pickle repo with a clean GGUF companion is no longer rejected.
…solver _llama_backend_active only consulted the auto resolver, so on a GPU box where auto resolves to sentence-transformers but the process already fell back to the llama-server backend at runtime (a torch or CUDA load/encode failure), it returned False and the settings endpoint hard-blocked a save whose ST pickle is flagged even though the process loads only inert GGUF. Add active_backend_is_llama, which reflects the actual built backend (True when the cached backend is a LlamaServerBackend, including a runtime fallback) and otherwise defers to the resolver as a fresh process would, and delegate _llama_backend_active to it.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 293a033510
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| raw = (config.EMBED_BACKEND or "auto").strip().lower() | ||
| key = _resolve_auto() if raw in _AUTO_ALIASES else raw | ||
| return key in _LLAMA_ALIASES |
There was a problem hiding this comment.
Return false for a cached ST backend
When a backend has already been built and it is not LlamaServerBackend, this falls through to _resolve_auto() instead of reporting the actual cached sentence-transformers backend. Because _get_backend() caches by the raw auto key, a later resolver change (for example the llama binary becoming visible or a GPU probe changing) can make /settings/embedding-model think llama is active and skip the new pickle scan even though this process will keep loading the saved model through the cached ST backend until reset. Return False as soon as backend is not None and is not a llama backend.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in c1e906b: once a backend is built, active_backend_is_llama() now returns isinstance(backend, LlamaServerBackend) directly, so a live sentence-transformers backend reports False and keeps its pickle gated even if the resolver would pick llama. The resolver is only consulted before any backend exists.
active_backend_is_llama() fell through to the config resolver whenever a backend was already built but was not llama-server, so a live sentence-transformers backend could report llama=True once the resolver picked llama (GPU heuristic or a runtime config change) and wrongly skip its pickle scan. Once a backend exists, return isinstance(backend, LlamaServerBackend) directly; only defer to the resolver before any backend is built.
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Problem
The RAG embedding model can be set at runtime through
PUT /api/settings/embedding-model. That path took a user-supplied repo id (plus an optionalforce), persisted it, and later handed it straight toSentenceTransformer(name, ...)in the backend process.SentenceTransformerdeserializes pickle weights (pytorch_model.bin) on load, so this is a model-artifact load.Every normal model-load path in Studio runs the artifact security gate first (
evaluate_file_security, and the remote-code consent scan), but this route ran neither:force=true, verification was skipped entirely.force, the only check wasis_embedding_model, which reads Hugging Facetags/pipeline_tag. That metadata is written by the repo owner, so it gates typos, not an attacker.The stored value then flowed to the load sink on the next dense search or ingestion. So an authenticated caller could point the embedding model at a repo Hugging Face flags as unsafe (or any repo at all with
force) and have it downloaded and loaded unscanned, bypassing the protections that guard the ordinary model-load paths.Fix
Run the malware/pickle scan (
evaluate_file_security) at both ends of this path:PUT /embedding-modelscans before it persists and returns 409 on a flagged repo. This runs even underforce:forcekeeps its legitimate role of skipping the is-embedding-model type check for offline or local repos Hugging Face cannot verify, but it no longer skips the security scan.core/rag/embeddings.pyscans again at the load sink, immediately beforeSentenceTransformer(...), so a name that arrives via env or the built-in default is covered too, not just names set through the API.evaluate_file_securityis metadata-only and fails open for local paths and when the Hub scan is unavailable, so offline and local-path installs are unaffected. The sink guard also never bricks the embedder on a gate import or lookup error; the settings endpoint (which has the caller's token for gated repos) is the primary enforcement point and the sink is defense in depth.Scope note on remote code: the embedder loads with
SentenceTransformerwithouttrust_remote_code, so theauto_mapremote-code consent gate is a no-op on this path (it keys on atrust_remote_code=Trueload). The concrete, reachable risk here is the pickle deserialization, which the malware gate covers; that is the gate this change adds.Tests
forceand is not persisted, and that a clean repo still saves._guard_model_securityraises on a flagged repo and passes a clean one.test_security_gate_consistency.pyasserting both the settings save path and the embedder load sink callevaluate_file_security, so a future refactor that drops either site fails in CI.Existing embedding and settings-route tests still pass.