Repository navigation
Resolve a sentence-transformers modules.json module class through the same trust gate as upstream - #12436
Conversation
A sentence-transformers model's modules.json "type" is model data: it comes from the model folder, or from the Hub through _module_path's hf_hub_download. _load_modules passed it to import_from_string, so the dotted path a repo named was imported and its top level code ran without the caller opting in. sentence-transformers 6.0 requires trust_remote_code=True for a module class outside sentence_transformers.*, since importing it runs third party code. We reimplement the module scan rather than calling their loader, so that gate did not apply to our path. Apply the same rules: - _resolve_module_class is the one place a type becomes a class. sentence_transformers.* resolves as before, anything else asks for consent, and with consent it goes through import_module_class on 6.x so the repo's own modeling file wins over a same named installed package. - _is_transformer_module_ref is a pure string test again. It used to import a candidate just to compare it against Transformer. Other spellings of Transformer are still picked up by the is Transformer comparison in _load_modules, after the class has been through the gate. - _load_modules resolves once per entry and before the module subfolder download, so a refused type fails the load instead of reaching the "could not download, skip and carry on" branch. - _check_module_config_class_refs covers the module's own config.json on sentence-transformers below 6, where Dense imports and calls activation_function, WordEmbeddings imports tokenizer_class and Router/Asym import every value in types with no gate. Upstream's own rules, and a no op on 6.x where the loaders already apply them. - Studio's two embedding loads pass the run's trust_remote_code, like every other load site in the worker. Models whose modules.json names sentence-transformers classes are unaffected: all 62 module classes the library ships still resolve without consent, as do the 4 distinct types declared across 18 embedders including the unsloth mirrors our notebooks load. Embeddings and a seeded LoRA embedding training run on embeddinggemma-300m, whose two Dense entries take this path, are unchanged.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
Security findingsAdvisory findings (1)ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
|
@codex security review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d282bbdc6a
ℹ️ 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".
| config_path = os.path.join(load_path, "config.json") | ||
| if not os.path.isfile(config_path): | ||
| return |
There was a problem hiding this comment.
Inspect each module's actual config filename
The sentence-transformers 5.x protection only reads config.json, but affected stock modules use other filenames: WordEmbeddings.config_file_name is wordembedding_config.json and Router/Asym uses router_config.json. A model can therefore declare the allowed sentence_transformers.models.Router type and put an attacker-controlled dotted path in the official router_config.json types map; this check returns before inspecting it, and Router.load() then passes that path to import_from_string even when trust_remote_code=False. Resolve the module's configured filename (including legacy fallbacks) rather than hard-coding config.json.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
You are right, and this was worse than a missed filename: the check covered Dense only, which inherits Module.config_file_name, and returned early for both modules it was actually written for. Confirmed in the 5.1 source, Router.config_file_name is router_config.json with a config.json legacy fallback and WordEmbeddings.config_file_name is wordembedding_config.json.
Fixed in d634ed3. The name now comes off the module class, keeping config.json as the fallback Router itself uses, and module_class is a required argument so a caller cannot quietly reduce the check back to config.json.
My first test deserved to miss this, since it called the helper directly with a config.json it wrote itself. The replacement goes through _load_modules with a real sentence_transformers.models.Router type, so the type is one the gate allows and the refusal has to come from reading the right config file. Against the previous commit it reports DID NOT RAISE for both Router and WordEmbeddings, and it passes with the fix.
| # Carry the consent decision into the modules.json module scan: a repo-declared | ||
| # module class outside sentence_transformers.* imports third-party code, so it | ||
| # loads only when the user opted in and the scan above cleared the repo. | ||
| trust_remote_code = config.get("trust_remote_code", False), |
There was a problem hiding this comment.
Scan modules.json code before forwarding consent
When an embedding run has trust_remote_code=True, this now allows _resolve_module_class to download and execute a repo-local class named by modules.json, but the preceding _model_load_security_error calls a consent scanner that skips a target whenever its Transformers configs have no auto_map (consent.py returns "no auto_map; trust_remote_code is a no-op"). Thus a sentence-transformers repo with a custom module and no auto_map bypasses the fingerprint scan and even its non-approvable CRITICAL-code block. The preflight must discover and scan modules.json module code before this flag is forwarded.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch, and the consent scan does read that way: evaluate_remote_code_consent_for_targets sets has_remote_code from _config_has_auto_map alone and returns early with "no auto_map; trust_remote_code is a no-op", so a repo whose only custom code is the modules.json module class never gets fingerprinted and never reaches the CRITICAL block that cannot be approved away.
Rather than widen the preflight here, I have made this path fail closed in 02d8ea4: both embedding loads now pass trust_remote_code = False explicitly, with the reasoning in a comment next to it. So the module scan refuses a class outside sentence_transformers.* in Studio regardless of what the run requested, and nothing can be fetched and executed on the strength of a consent decision that never looked at it.
That also costs nothing today. The path passed no trust_remote_code at all before this change, so this is the same effective behaviour, and no embedding model Studio offers declares a module type outside sentence_transformers.*. Forwarding the flag is the right thing once the preflight can enumerate modules.json types, locate the module code they name and scan plus fingerprint it like auto_map code, which is a larger change than belongs in this one.
The consent scan in front of the embedding load decides purely on auto_map (utils/security/consent.py returns "no auto_map; trust_remote_code is a no-op"), so a repo whose only custom code is a modules.json module class is never fingerprinted and never hits the non-approvable CRITICAL block. Forwarding the run's trust_remote_code into the module scan would let that class be fetched and executed unscanned, so pass False explicitly and leave a note: the flag can be forwarded once the preflight discovers and scans modules.json module code as well. This matches what the embedding path already did before the gate landed, since it passed no trust_remote_code at all, so nothing that loaded before stops loading.
|
@codex review |
There was a problem hiding this comment.
🛡️ Codex Security Review
Here are some automated security review suggestions for this pull request.
Reviewed commit: d282bbdc6a
ℹ️ About Codex security reviews in GitHub
This is an experimental Codex feature. Security reviews are triggered when:
- You comment "@codex security review"
- A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review
Once complete, Codex will leave suggestions, or a comment if no findings are found.
| # Carry the consent decision into the modules.json module scan: a repo-declared | ||
| # module class outside sentence_transformers.* imports third-party code, so it | ||
| # loads only when the user opted in and the scan above cleared the repo. | ||
| trust_remote_code = config.get("trust_remote_code", False), |
There was a problem hiding this comment.
🛡️ Codex Security Review
Security: Scan modules.json code before trusting embedding models
When Studio has managed accounts and sentence-transformers >=6, an authenticated managed user can start an embedding job with trust_remote_code=true against a repo whose modules.json names repo Python but whose configs omit auto_map. _model_load_security_error then returns “no auto_map” before the managed-account denial/static scan, yet this new argument lets _resolve_module_class execute that unscanned code as the Studio OS user. Extend the consent scan, fingerprint, and managed-account check to modules.json classes, including external refs, before forwarding trust.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Same root cause as the thread on the other call site, and the managed-account point sharpens it: managed_remote_code_refused sits behind the same early return, so a repo with no auto_map never reaches it either.
Fixed in 02d8ea4 by not forwarding at all. Both embedding loads now pass trust_remote_code = False explicitly, so the module scan refuses a class outside sentence_transformers.* whatever the run asked for, and there is nothing for an unscanned consent decision to authorise. Extending the consent scan, fingerprint and managed-account check to modules.json classes is the right way to make the flag forwardable, and that is worth doing on its own rather than inside this change.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 02d8ea4a81
ℹ️ 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".
| # sentence-transformers >= 6 applies these gates in the module loaders themselves. | ||
| return | ||
|
|
||
| config_path = os.path.join(load_path, "config.json") |
There was a problem hiding this comment.
Validate nested Router module configs recursively
On sentence-transformers 5.x, a Router can declare only allowed classes such as sentence_transformers.models.Dense in its types map and then load each child module from a subdirectory; a child Dense config.json can still name an attacker-controlled activation_function, which Dense.load() imports and calls. This check examines only one config at the Router root and never descends into those child directories, so loading such a repository executes code even with trust_remote_code=False; selecting router_config.json instead of config.json is therefore not sufficient unless the referenced child configs are also validated.
Useful? React with 👍 / 👎.
The sentence-transformers < 6 check only opened config.json, but a module names its own file: Router uses router_config.json and falls back to config.json, WordEmbeddings uses wordembedding_config.json, and config.json is Module's default and so Dense's. It therefore covered Dense alone and returned early for the two modules it was written for, so a repo could declare the allowed sentence_transformers.models.Router type and put its dotted path in the official router_config.json types map. Resolve the name off the module class instead, keeping config.json as the fallback Router itself uses, and make module_class a required argument so a caller cannot quietly reduce the check to config.json again. The test now goes through _load_modules rather than calling the helper, so it covers the wiring too: without this it does not raise for either module, with it both are refused. Also trims the comments across the change.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d634ed3cb7
ℹ️ 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".
| refs += [ | ||
| (key, config[key], prefix) | ||
| for key, prefix in FastSentenceTransformer._MODULE_CONFIG_CLASS_REFS | ||
| if isinstance(config.get(key), str) |
There was a problem hiding this comment.
Restrict activation checks to importing module classes
With sentence-transformers 5.x, this applies the torch.* rule to every module config, although only Dense.load() imports activation_function. The stock sentence_transformers.sparse_encoder.models.SpladePooling instead stores enum values such as "relu" or "log1p_relu" in that field and never imports them, so a valid sparse model listing this module directly in modules.json is now rejected before loading. Apply this validation only to module classes whose loaders actually resolve the field.
Useful? React with 👍 / 👎.
FastSentenceTransformerreads the module list from a model'smodules.jsonand resolves each entry'stypeto a class. That field is model data: it arrives from the model folder, or from the Hub via_module_path'shf_hub_download. We were handing it straight tosentence_transformers.util.import_from_string, so the dotted path a repo named got imported, and its top level code ran, with no opt in from the caller.sentence-transformers settled this upstream in 6.0: a module class outside
sentence_transformers.*needstrust_remote_code=True, because importing it runs third party code. Since we reimplement the module scan in_load_modulesrather than calling their loader, their gate never applied to our path. This brings our loader in line with theirs.What changed
unsloth/models/sentence_transformer.py_resolve_module_class, the single place amodules.jsontypebecomes a class. Anything undersentence_transformers.*resolves as before. Anything else needstrust_remote_code=True, and the message names the class and points at the repo or local folder so it is clear what is being asked for. With consent it routes throughimport_module_classon sentence-transformers 6.x, which prefers the repo's own modeling file over a same named installed package, and falls back toimport_from_stringon 5.x._is_transformer_module_refis now a pure string test. It used to import a candidate just to compare it againstTransformer, which is the same import by another route. Refs that spellTransformersome other way are still picked up, by theis Transformercomparison in_load_modulesafter the class has been through the gate._load_modulesresolves once per entry and before the module subfolder download, so a refused type fails the load instead of landing in the "could not download, skip and carry on" branch. Resolving once also drops a duplicate Hub round trip for a consented repo local class._check_module_config_class_refscovers a second door on sentence-transformers below 6. A module's ownconfig.jsonholds further dotted paths, and those loaders resolve them with no gate:Denseimports and then callsactivation_function,WordEmbeddingsimportstokenizer_class,RouterandAsymimport every value intypes. An in namespacetype, which the gate rightly allows, would otherwise reach them. The rules are upstream's own,torch.*for the activation andsentence_transformers.*for the rest, and the check is a no op on 6.x where the loaders already apply them.studio/backend/core/training/worker.pyfrom_pretrainedcalls passtrust_remote_code = Falseexplicitly, with a note on why. Forwarding the run's flag was the obvious move and is wrong here: the consent scan in front of this load decides purely onauto_map, returning "no auto_map; trust_remote_code is a no-op", so a repo whose only custom code is amodules.jsonmodule class is never fingerprinted and never reaches the non-approvable CRITICAL block. Forwarding consent would let exactly that class be fetched and run unscanned. The flag can be forwarded once the preflight discovers and scansmodules.jsonmodule code as well. This is what the path already did before the gate landed, since it passed notrust_remote_codeat all, so nothing that loaded before stops loading.Compatibility
No behaviour change for a model whose
modules.jsonnames sentence-transformers classes, which is every embedder I could find. Checks I ran:modules.jsonfrom 18 embedders, theunsloth/*mirrors our notebooks load plus bge, MiniLM, mpnet, e5, gte, bge-m3, nomic, mxbai, Qwen3-Embedding 0.6B/4B/8B and embeddinggemma: 4 distinct types between them, allsentence_transformers.models.*, none refused.embeddinggemma-300mis the useful case here, since its twoDenseentries take the resolve path rather than the Transformer fast path. Loaded and trained fine, and itsDenseconfigs declaretorch.nn.modules.linear.Identity, which is what the 5.x check allows.embeddinggemma-300m, the EmbeddingGemma notebook's flow with a fixed seed and fixed data: losses, grad norms, final training loss and post training embeddings all identical before and after. Peak reserved memory lands on either 0.76 GB or 0.88 GB depending on allocator state, with both values seen on both sides across two repeats each, so it carries no signal either way.bge-small-en-v1.5,all-MiniLM-L6-v2andembeddinggemma-300mare identical before and after, down to the values.tests/test_st_modules_json_trust_gate.pyis new, and covers the untrusted type being refused without being imported, the refusal failing the load rather than skipping the entry, consent still loading a custom type, every stock type still resolving, the Transformer fast path, and the 5.x config check both firing and staying quiet on a realDenseconfig.tests/test_rag_embedding_identity.pyhas 11 failures and 5 errors, identical onmain, so they are not from this change.trust_remote_code=True. The jina stylecustom_st.Transformerrepos are the shape to watch, and those already failed onmainwithModuleNotFoundError, since the repo's.pyis not importable; with consent they now load through the dynamic module path instead.Not covered
Windows and macOS were not exercised, though nothing here is platform specific. I did not load a consented remote code embedder end to end, so the
import_module_classpath with a real repo hosted modeling file is reasoned from upstream's source rather than run.