Skip to content

Resolve a sentence-transformers modules.json module class through the same trust gate as upstream - #12436

Merged
danielhanchen merged 3 commits into
mainfrom
harden-st-modules-trust-gate
Oct 1, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
harden-st-modules-trust-gate

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

FastSentenceTransformer reads the module list from a model's modules.json and resolves each entry's type to a class. That field is model data: it arrives from the model folder, or from the Hub via _module_path's hf_hub_download. We were handing it straight to sentence_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.* needs trust_remote_code=True, because importing it runs third party code. Since we reimplement the module scan in _load_modules rather 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

  • New _resolve_module_class, the single place a modules.json type becomes a class. Anything under sentence_transformers.* resolves as before. Anything else needs trust_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 through import_module_class on sentence-transformers 6.x, which prefers the repo's own modeling file over a same named installed package, and falls back to import_from_string on 5.x.
  • _is_transformer_module_ref is now a pure string test. It used to import a candidate just to compare it against Transformer, which is the same import by another route. Refs that spell Transformer some other way 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 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_refs covers a second door on sentence-transformers below 6. A module's own config.json holds further dotted paths, and those loaders resolve them with no gate: Dense imports and then calls activation_function, WordEmbeddings imports tokenizer_class, Router and Asym import every value in types. An in namespace type, which the gate rightly allows, would otherwise reach them. The rules are upstream's own, torch.* for the activation and sentence_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.py

  • The two embedding from_pretrained calls pass trust_remote_code = False explicitly, 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 on auto_map, returning "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 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 scans modules.json module code as well. This is what the path already did before the gate landed, since it passed no trust_remote_code at all, so nothing that loaded before stops loading.

Compatibility

No behaviour change for a model whose modules.json names sentence-transformers classes, which is every embedder I could find. Checks I ran:

  • Every module class sentence-transformers ships, enumerated from the installed package rather than sampled: 62 of 62 still resolve with no consent, 0 refused.
  • modules.json from 18 embedders, the unsloth/* 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, all sentence_transformers.models.*, none refused.
  • embeddinggemma-300m is the useful case here, since its two Dense entries take the resolve path rather than the Transformer fast path. Loaded and trained fine, and its Dense configs declare torch.nn.modules.linear.Identity, which is what the 5.x check allows.
  • LoRA embedding training on 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.
  • Embeddings from bge-small-en-v1.5, all-MiniLM-L6-v2 and embeddinggemma-300m are identical before and after, down to the values.
  • tests/test_st_modules_json_trust_gate.py is 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 real Dense config.
  • Existing suites: 144 passed 2 skipped across the sentence-transformers and remote code tests, and 159 passed across the Studio embedding security gate, consent gate and approval cache tests. tests/test_rag_embedding_identity.py has 11 failures and 5 errors, identical on main, so they are not from this change.
  • Checked against sentence-transformers 6.1.0 and 5.1.0. On 5.x the gate is now stricter than the installed library, which is the 6.0 behaviour applied one version early and worth knowing about: a repo with a custom module type that resolved only because an identically named package happened to be installed will now ask for trust_remote_code=True. The jina style custom_st.Transformer repos are the shape to watch, and those already failed on main with ModuleNotFoundError, since the repo's .py is 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_class path with a real repo hosted modeling file is reasoned from upstream's source rather than run.

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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-01T13:54:15.969977Z d634ed3 Manual request
🔒 Security Review ✅ Completed 2026-10-01T13:39:08.879657Z d282bbd Manual request

Security findings

Advisory findings (1)

ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment thread unsloth/models/sentence_transformer.py Outdated
Comment on lines +1294 to +1296
config_path = os.path.join(load_path, "config.json")
if not os.path.isfile(config_path):
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

Comment thread studio/backend/core/training/worker.py Outdated
Comment on lines +5136 to +5139
# 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),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛡️ 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.

Comment thread studio/backend/core/training/worker.py Outdated
# 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),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛡️ Codex Security Review

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment thread unsloth/models/sentence_transformer.py Outdated
# sentence-transformers >= 6 applies these gates in the module loaders themselves.
return

config_path = os.path.join(load_path, "config.json")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +1319 to +1322
refs += [
(key, config[key], prefix)
for key, prefix in FastSentenceTransformer._MODULE_CONFIG_CLASS_REFS
if isinstance(config.get(key), str)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

@danielhanchen
danielhanchen merged commit d0b3a7b into main Oct 1, 2026
12 of 55 checks passed
@danielhanchen
danielhanchen deleted the harden-st-modules-trust-gate branch October 1, 2026 13:54
danielhanchen added a commit that referenced this pull request Oct 1, 2026
* Fix the tests left red on main by #12408, #12382 and #12436

* Trigger version-compat-ci on the trust-gate test and guard every file it runs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant