Repository navigation
Harden model fetching - #6391
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces a security consent gate and static repository scanner to secure the execution of custom model code (trust_remote_code). It adds trusted organization verification to prevent local path spoofing, integrates a consent dialog into the frontend, and ensures metadata probes remain code-free. The reviewer feedback highlights a missing import of types in hardware.py that would cause a runtime NameError. Additionally, the feedback points out several places where hf_token is ignored during configuration loading, which would break private repository access. Finally, the reviewer suggests exposing and mapping a blocked status in the scan payload to allow the frontend to conditionally prompt users only when a model is actually blocked, avoiding redundant prompts or silent load failures.
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.
| def _to_ns(d): | ||
| if isinstance(d, dict): | ||
| return types.SimpleNamespace(**{k: _to_ns(v) for k, v in d.items()}) | ||
| return d |
There was a problem hiding this comment.
The types module is not imported within this function or at the top of the file, which will cause a NameError when attempting to access types.SimpleNamespace at runtime.
To prevent runtime crashes, import SimpleNamespace directly from types inside the function (similar to how it is done in routes/models.py).
| def _to_ns(d): | |
| if isinstance(d, dict): | |
| return types.SimpleNamespace(**{k: _to_ns(v) for k, v in d.items()}) | |
| return d | |
| from types import SimpleNamespace | |
| def _to_ns(d): | |
| if isinstance(d, dict): | |
| return SimpleNamespace(**{k: _to_ns(v) for k, v in d.items()}) | |
| return d |
| ) | ||
| from utils.transformers_version import _load_config_json | ||
|
|
||
| cfg = _load_config_json(model_name) |
There was a problem hiding this comment.
The hf_token parameter passed to _load_config_for_gpu_estimate is currently ignored when calling _load_config_json(model_name).
This is a regression from the previous implementation (which passed token=hf_token to AutoConfig.from_pretrained). It will prevent loading configurations for private or gated Hugging Face repositories during GPU/VRAM estimation. Please update _load_config_json to accept a token or hf_token parameter and forward it here.
| cfg = _load_config_json(model_name) | |
| cfg = _load_config_json(model_name, token=hf_token) |
| try: | ||
| from utils.transformers_version import _load_config_json | ||
| cfg = _load_config_json(model_name) or {} | ||
| return bool(cfg.get("auto_map")) |
There was a problem hiding this comment.
The hf_token parameter passed to _config_has_auto_map is ignored when calling _load_config_json(model_name).
This will cause the auto-map check to fail for private or gated repositories that require authentication. Please update _load_config_json to accept a token parameter and forward hf_token here.
| return bool(cfg.get("auto_map")) | |
| cfg = _load_config_json(model_name, token=hf_token) or {} |
| model_name, trust_remote_code = _trust, token = hf_token | ||
| ) | ||
| max_position_embeddings = _get_max_position_embeddings(_ac) | ||
| _cfg = _load_config_json(model_name) |
There was a problem hiding this comment.
The hf_token available in the request is ignored when calling _load_config_json(model_name).
This is a regression from the previous implementation (which passed token=hf_token to AutoConfig.from_pretrained). It will prevent retrieving model configurations for private or gated repositories during metadata lookups. Please forward hf_token to _load_config_json.
| _cfg = _load_config_json(model_name) | |
| _cfg = _load_config_json(model_name, token=hf_token) |
| return { | ||
| "error_kind": ( | ||
| "remote_code_consent_required" if self.approvable else "remote_code_blocked" | ||
| ), | ||
| "model_name": self.model_name, | ||
| "has_remote_code": self.has_remote_code, | ||
| "approvable": self.approvable, | ||
| "fingerprint": self.fingerprint, | ||
| "max_severity": self.max_severity, | ||
| "findings": self.findings, | ||
| "findings_summary": self.findings_summary, | ||
| "reason": self.reason, | ||
| } |
There was a problem hiding this comment.
The response_payload dictionary does not include the blocked status of the decision.
Exposing "blocked": self.blocked in the payload is highly recommended so that the frontend can determine if a model with custom code actually requires a consent prompt (e.g., if it has CRITICAL findings, or HIGH findings on a third-party repo) when trustRemoteCode is already globally enabled. This avoids deadlocking the user or double-prompting for clean/first-party models.
| return { | |
| "error_kind": ( | |
| "remote_code_consent_required" if self.approvable else "remote_code_blocked" | |
| ), | |
| "model_name": self.model_name, | |
| "has_remote_code": self.has_remote_code, | |
| "approvable": self.approvable, | |
| "fingerprint": self.fingerprint, | |
| "max_severity": self.max_severity, | |
| "findings": self.findings, | |
| "findings_summary": self.findings_summary, | |
| "reason": self.reason, | |
| } | |
| return { | |
| "error_kind": ( | |
| "remote_code_consent_required" if self.approvable else "remote_code_blocked" | |
| ), | |
| "model_name": self.model_name, | |
| "has_remote_code": self.has_remote_code, | |
| "blocked": self.blocked, | |
| "approvable": self.approvable, | |
| "fingerprint": self.fingerprint, | |
| "max_severity": self.max_severity, | |
| "findings": self.findings, | |
| "findings_summary": self.findings_summary, | |
| "reason": self.reason, | |
| } |
| if (validation.requires_trust_remote_code && !trustRemoteCode) { | ||
| throw new Error(getTrustRemoteCodeRequiredMessage(displayName)); | ||
| const approved = await confirmRemoteCodeIfNeeded({ | ||
| modelName: modelId, | ||
| requiresTrustRemoteCode: true, | ||
| onApprove: (fp) => { | ||
| trustRemoteCode = true; | ||
| approvedRemoteCodeFingerprint = fp; | ||
| }, | ||
| }); | ||
| if (!approved) { | ||
| throw new Error(getTrustRemoteCodeRequiredMessage(displayName)); | ||
| } | ||
| } |
There was a problem hiding this comment.
If trustRemoteCode is already true (e.g., from a saved setting or previous session), the frontend completely bypasses confirmRemoteCodeIfNeeded.
However, if the model has CRITICAL findings, or HIGH findings on a third-party repository, the backend's load-time consent gate will return blocked = True because approved_remote_code_fingerprint is null (since the prompt was skipped). This will cause the load to fail silently on the backend, deadlocking the user from loading these models.
To fix this, we should always run confirmRemoteCodeIfNeeded if the model has custom code, but let the hook decide whether to show the dialog based on whether the scan is actually blocked (by exposing blocked in the scan API response).
| if (validation.requires_trust_remote_code && !trustRemoteCode) { | |
| throw new Error(getTrustRemoteCodeRequiredMessage(displayName)); | |
| const approved = await confirmRemoteCodeIfNeeded({ | |
| modelName: modelId, | |
| requiresTrustRemoteCode: true, | |
| onApprove: (fp) => { | |
| trustRemoteCode = true; | |
| approvedRemoteCodeFingerprint = fp; | |
| }, | |
| }); | |
| if (!approved) { | |
| throw new Error(getTrustRemoteCodeRequiredMessage(displayName)); | |
| } | |
| } | |
| if (validation.requires_trust_remote_code) { | |
| const approved = await confirmRemoteCodeIfNeeded({ | |
| modelName: modelId, | |
| requiresTrustRemoteCode: trustRemoteCode, | |
| onApprove: (fp) => { | |
| trustRemoteCode = true; | |
| approvedRemoteCodeFingerprint = fp; | |
| }, | |
| }); | |
| if (!approved) { | |
| throw new Error(getTrustRemoteCodeRequiredMessage(displayName)); | |
| } | |
| } |
| if (!scan.requiresTrustRemoteCode) return true; // no custom code -> nothing to confirm | ||
|
|
||
| const confirmed = await useRemoteCodeConsentDialogStore | ||
| .getState() | ||
| .requestConsent(scan); | ||
| if (!confirmed) return false; | ||
| onApprove(scan.fingerprint); | ||
| return true; | ||
| } |
There was a problem hiding this comment.
If the user has already enabled trustRemoteCode globally or in their settings, we should avoid prompting them again for clean or trusted first-party models. However, we must still prompt them if the scan is actually blocked (i.e., has CRITICAL findings, or HIGH findings on a third-party repo) to obtain the required fingerprint approval and prevent a silent backend load failure.
By checking scan.blocked (which should be exposed from the backend), we can conditionally prompt only when necessary.
if (!scan.requiresTrustRemoteCode) return true;
const needsPrompt = !requiresTrustRemoteCode || scan.blocked;
if (!needsPrompt) {
onApprove(scan.fingerprint);
return true;
}
const confirmed = await useRemoteCodeConsentDialogStore
.getState()
.requestConsent(scan);
if (!confirmed) return false;
onApprove(scan.fingerprint);
return true;| export interface RemoteCodeScan { | ||
| requiresTrustRemoteCode: boolean; | ||
| approvable: boolean; // false for CRITICAL -> the user cannot override | ||
| maxSeverity: RemoteCodeSeverity | null; | ||
| fingerprint: string | null; | ||
| findings: RemoteCodeFinding[]; | ||
| findingsSummary: string; | ||
| modelName: string; | ||
| } |
There was a problem hiding this comment.
Add the blocked field to the RemoteCodeScan interface to support conditional prompting when trustRemoteCode is already enabled.
| export interface RemoteCodeScan { | |
| requiresTrustRemoteCode: boolean; | |
| approvable: boolean; // false for CRITICAL -> the user cannot override | |
| maxSeverity: RemoteCodeSeverity | null; | |
| fingerprint: string | null; | |
| findings: RemoteCodeFinding[]; | |
| findingsSummary: string; | |
| modelName: string; | |
| } | |
| export interface RemoteCodeScan { | |
| requiresTrustRemoteCode: boolean; | |
| approvable: boolean; // false for CRITICAL -> the user cannot override | |
| maxSeverity: RemoteCodeSeverity | null; | |
| fingerprint: string | null; | |
| findings: RemoteCodeFinding[]; | |
| findingsSummary: string; | |
| modelName: string; | |
| blocked: boolean; | |
| } |
| return { | ||
| requiresTrustRemoteCode: Boolean( | ||
| data.requires_trust_remote_code ?? data.has_remote_code, | ||
| ), | ||
| approvable: data.approvable ?? true, | ||
| maxSeverity: (data.max_severity as RemoteCodeSeverity | null) ?? null, | ||
| fingerprint: data.fingerprint ?? null, | ||
| findings, | ||
| findingsSummary: data.findings_summary ?? "", | ||
| modelName: data.model_name ?? modelName, | ||
| }; | ||
| } |
There was a problem hiding this comment.
Map the blocked field from the API response to the frontend RemoteCodeScan object.
return {
requiresTrustRemoteCode: Boolean(
data.requires_trust_remote_code ?? data.has_remote_code,
),
approvable: data.approvable ?? true,
maxSeverity: (data.max_severity as RemoteCodeSeverity | null) ?? null,
fingerprint: data.fingerprint ?? null,
findings,
findingsSummary: data.findings_summary ?? "",
modelName: data.model_name ?? modelName,
blocked: data.blocked ?? false,
};There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ad7ff2ea65
ℹ️ 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.transformers_version import _load_config_json | ||
|
|
||
| cfg = _load_config_json(model_name) or {} |
There was a problem hiding this comment.
Use the HF token before treating auto_map as absent
When a gated/private Hub model has custom code, this helper ignores its hf_token argument and calls _load_config_json, which fetches config via unauthenticated urllib and caches failures. If the caller loads with trust_remote_code=True, a 401 or transient config miss becomes {} here, the gate returns “no auto_map”, and the subsequent authenticated from_pretrained(..., token=..., trust_remote_code=True) can execute repo code without any scan or fingerprint check. Use an authenticated config read, or fail into the unscannable/consent path instead of treating an unreadable config as no remote code.
Useful? React with 👍 / 👎.
| export async function getRemoteCodeScan(modelName: string): Promise<RemoteCodeScan> { | ||
| const response = await authFetch( | ||
| `/api/models/remote-code-scan/${encodeModelPath(modelName)}`, |
There was a problem hiding this comment.
Pass the user HF token to remote-code scans
The backend scan route accepts hf_token, but this new client API never sends the token that chat/training already use for validation and loading. For a private or gated model with auto_map, the preflight scan runs unauthenticated, so the dialog cannot reliably show findings or set the approval fingerprint before the authenticated load path needs trust_remote_code. Plumb the token through confirmRemoteCodeIfNeeded into this request so gated custom-code models are scanned with the same credentials used to load them.
Useful? React with 👍 / 👎.
| if approved: | ||
| blocked, reason = False, "approved by fingerprint" |
There was a problem hiding this comment.
Keep CRITICAL findings non-overridable
When a scan reports CRITICAL findings, the response marks it non-approvable and the UI hides the enable button, but the server accepts a matching approved_remote_code_fingerprint before checking sev == CRITICAL. A caller can get the fingerprint from the scan response and submit it directly to a load endpoint, causing code that this gate labels as a hard block to execute. Only honor approved_fingerprint for approvable severities.
Useful? React with 👍 / 👎.
| root = Path(normalize_path(model_name)).expanduser() | ||
| cfg_path = root / "config.json" | ||
| cfg = json.loads(cfg_path.read_text()) if cfg_path.is_file() else {} | ||
| wanted = _auto_map_py(cfg) | {p.name for p in root.glob("*.py")} |
There was a problem hiding this comment.
Scan local custom-code helpers recursively
For local model paths, the scanner only fingerprints top-level *.py files, while a custom modeling_*.py can import helper modules from packages/subdirectories that are executed during trust_remote_code=True loads. In that case the dialog and backend approval are based on a clean top-level file, but malicious nested Python is neither scanned nor included in the fingerprint. Mirror the remote branch by walking all local .py files recursively.
Useful? React with 👍 / 👎.
| @@ -483,7 +485,17 @@ export function useChatModelRuntime() { | |||
| gguf_variant: ggufVariant ?? null, | |||
| }); | |||
| if (validation.requires_trust_remote_code && !trustRemoteCode) { | |||
There was a problem hiding this comment.
Prompt even when custom code is already enabled
When the Chat Settings toggle is already on, this condition skips the new consent flow, leaving approvedRemoteCodeFingerprint as null while still sending trust_remote_code: true. For third-party custom-code models with HIGH findings, the backend now requires a matching fingerprint, so users who already had custom code enabled get a load failure instead of the approval dialog. Run the scan/approval whenever the model requires remote code and no valid fingerprint has been collected.
Useful? React with 👍 / 👎.
| and (_mn_lower.startswith("unsloth/") or _mn_lower.startswith("nvidia/")) | ||
| # Genuine first-party Hub repo only, not a local-path/spoof | ||
| # that starts with "unsloth/". | ||
| and is_trusted_org_repo(model_name) |
There was a problem hiding this comment.
Verify trusted private repos with the request token
This auto-enable check performs Hub verification without the hf_token already extracted for the load. For private or gated unsloth/ or nvidia/ Nemotron repos, is_trusted_org_repo fails closed on the unauthenticated lookup, so the new trusted-org hardening disables the Nemotron trust_remote_code workaround even though the user supplied credentials. Pass the load token into this check (and the analogous training/export checks) so authenticated trusted repos still auto-enable.
Useful? React with 👍 / 👎.
| except Exception: | ||
| continue |
There was a problem hiding this comment.
Treat skipped remote code files as unscannable
If one .py file fails to download, the scanner silently omits it and still returns a non-empty files map when any other Python file downloaded. A transient/auth failure on an auto_map target can therefore produce a clean fingerprint that excludes code which transformers may successfully fetch and execute moments later. Return the unscannable path or fail the scan when any required Python file cannot be read, rather than approving a partial snapshot.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bfa1968428
ℹ️ 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".
| if config.get("trust_remote_code", False): | ||
| from utils.security import evaluate_remote_code_consent | ||
| _rc = evaluate_remote_code_consent( | ||
| model_name, | ||
| hf_token = config.get("hf_token") or None, | ||
| trust_remote_code = True, | ||
| approved_fingerprint = config.get("approved_remote_code_fingerprint"), |
There was a problem hiding this comment.
Move the consent gate before the MLX fast path
On Apple Silicon, run_training_process returns from the DeviceType.MLX branch before reaching this new gate, while _run_mlx_training later passes trust_remote_code into FastMLXModel.from_pretrained. A direct/resume /api/training/start request with trust_remote_code=true can therefore execute a model repo's auto_map code on MLX without the backend scan or CRITICAL hard block. Run the same consent check before the MLX branch calls _run_mlx_training.
Useful? React with 👍 / 👎.
| cache_key = (name, verify_remote) | ||
| if cache_key in _verdict_cache: | ||
| return _verdict_cache[cache_key] |
There was a problem hiding this comment.
Include the HF token in trusted-org cache keys
The cache key ignores hf_token, so a failed unauthenticated Hub verification for a private/gated unsloth/... or nvidia/... repo is reused even when a later caller supplies a valid token; conversely a token-authenticated verdict can leak to unauthenticated checks. This affects even paths that correctly pass hf_token into is_trusted_org_repo, causing trusted private repos with HIGH findings to be blocked or auto-enable decisions to use another credential's verdict. Key the cache by a token fingerprint as well as the name/verify mode.
Useful? React with 👍 / 👎.
| gguf_variant: sel.ggufVariant ?? null, | ||
| trust_remote_code: trustRemoteCode, | ||
| trust_remote_code: loadTrustRemoteCode, | ||
| approved_remote_code_fingerprint: approvedRemoteCodeFingerprint, |
There was a problem hiding this comment.
Preserve approval when reloading the active compare model
When a generalized-compare selection is already the active model, the validation/consent block above is skipped, so approvedRemoteCodeFingerprint remains null; this loadModel call still reloads the subprocess. For an already-loaded third-party custom-code model with HIGH findings that the user approved earlier, compare reloads it without the required fingerprint and the backend consent gate rejects it. Either skip the reload for isAlreadyActive or retain and resend the active model's approval fingerprint.
Useful? React with 👍 / 👎.
| cfg_path = hf_hub_download(repo_id = model_name, filename = "config.json", token = hf_token) | ||
| return bool(json.loads(Path(cfg_path).read_text()).get("auto_map")) |
There was a problem hiding this comment.
Scan tokenizer custom code before skipping the gate
This check treats a readable config.json without auto_map as proof that trust_remote_code is a no-op, but Transformers also executes custom tokenizer/processor code declared in files such as tokenizer_config.json when the load paths pass trust_remote_code to AutoTokenizer/Fast*Model.from_pretrained. A repo with only tokenizer_config.json auto_map therefore returns has_remote_code=False here and its tokenization_*.py can run without any scan or fingerprint. Include tokenizer/processor auto_map declarations in the preflight decision.
Useful? React with 👍 / 👎.
| _rc = evaluate_remote_code_consent( | ||
| config["model_name"], | ||
| hf_token = hf_token, |
There was a problem hiding this comment.
Gate LoRA base-model code instead of the adapter path
For LoRA adapters, mc.base_model is the repo whose code will be loaded by FastLanguageModel.from_pretrained, but this gate scans only config["model_name"] (the adapter path/id). If the adapter config points at a custom-code base model, the adapter itself usually has no config.json auto_map, so the gate returns “no remote code” while the base model's repo code executes with trust_remote_code=True. Resolve and scan the effective base model whenever mc.is_lora has a base.
Useful? React with 👍 / 👎.
| // "Enable custom code" toggle is on: the worker now requires a | ||
| // matching fingerprint, which only the dialog produces. Clean | ||
| // custom code returns immediately without a dialog. | ||
| if (validation.requires_trust_remote_code) { |
There was a problem hiding this comment.
Detect auto_map instead of relying on YAML validation
Fresh evidence is that /api/inference/validate still sets requires_trust_remote_code from load_inference_config(...).get('trust_remote_code'), so third-party repos that declare auto_map only in their raw config but have no Studio YAML entry skip this consent block. With the legacy toggle enabled, those loads proceed with approved_remote_code_fingerprint=null and either fail at the backend for HIGH findings or run clean/MEDIUM custom code without showing the new scan dialog. Run confirmRemoteCodeIfNeeded regardless (it already no-ops when there is no auto_map) or make validation report raw auto_map.
Useful? React with 👍 / 👎.
| wanted = set(_auto_map_py(cfg)) | ||
| try: | ||
| wanted |= {f for f in list_repo_files(model_name, token = hf_token) if f.endswith(".py")} |
There was a problem hiding this comment.
Avoid scanning unrelated repository Python files
This expands the scan from the auto_map targets to every .py file in the Hub repo. For a custom-code model that also ships an unused example, conversion script, or training utility with a HIGH/CRITICAL pattern, the consent gate can require approval or hard-block even though Transformers would not import that file for the model load. Limit the remote scan to the auto_map modules plus their import closure, or do not let unrelated files affect the blocking fingerprint.
Useful? React with 👍 / 👎.
| module = ref.rsplit(".", 1)[0] | ||
| out.add(module.split("--")[-1] + ".py") |
There was a problem hiding this comment.
Follow external auto_map repositories
When an auto_map entry uses the supported other/repo--module.Class form, this parsing discards the external repo id and downloads module.py from the model repo instead. In that case the scan and fingerprint cover the wrong file (or nothing), while Transformers can fetch and execute the code from other/repo once trust_remote_code=True is used. Preserve the repo part and scan/download the referenced code repository before approving the load.
Useful? React with 👍 / 👎.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
Add a load-path consent gate that scans a model's auto_map repository code before it executes and blocks CRITICAL/HIGH findings unless the user pins approval of that exact code version. Capability detection stays code-free, reading raw config.json instead of AutoConfig. - Scan config.json and tokenizer_config.json auto_map, nested local helpers, and external owner/name--module repos; fail closed on partial downloads. - Gate inference, training, and export workers, including the MLX path and a LoRA's base model, and report requires_trust_remote_code from the raw config so chat and auto-load surface the dialog. - Verify trusted-org auto-enable against the Hub with the request token and key the verdict cache by token; reject local-path and spoofed names. - Add a consent dialog showing the flagged file, line, and surrounding code. - Thread hf_token through the scan and load paths for gated repos.
- Send the HF token for remote-code scans in the POST body, not the URL, so it never lands in a log or browser history. - Collect tokenizer_config.json auto_map files directly instead of relying only on the repo file listing. - Resolve a LoRA's base model for the validate flag and the scan endpoint so the dialog scans the code the workers actually gate. - Pass the request token to the training YAML trusted-org auto-enable. - Resend a previously approved fingerprint when rolling back to a custom-code model after a failed switch.
458cad3 to
cc0fa75
Compare
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
… downloads The per-model consent dialog is now the single approval path for custom (auto_map) code in chat, so three leftovers from before it existed are removed: - Remove the "Enable custom code" switch from Chat Settings and stop persisting trust_remote_code, so a previously saved blanket-on cannot linger and load a model without going through per-version review. The flag stays as an internal YAML/preset default (e.g. first-party auto-enable); the load path still gates every custom-code load on a fingerprint only the dialog produces. - Reword the decline message and the auto-load toast to describe approving the model's code from the dialog, not a missing settings toggle. - On decline, purge the repo the scan downloaded so untrusted code is not left on disk. A new /api/models/discard-remote-code endpoint deletes only a metadata-only cache entry the scan created; it refuses local paths, loaded models, and any repo with weight files cached, so a model the user already had or pre-downloaded is always left untouched. The frontend only calls it when the scan reported created_by_scan. Adds discard-endpoint tests (delete metadata-only, refuse on weights/gguf, refuse local, no-op when not cached) and a created_by_scan payload assertion.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
The Export page kept a "Trust remote code" switch (default on) next to the HF token field. Like chat, custom (auto_map) code should be approved per model through the load-time review dialog, not a persistent blanket switch, so the toggle is removed. The export load path already routes through the same consent dialog: an HF source now starts with trust_remote_code off and only enables it when the user approves the scanned code in the dialog (a local checkpoint the user exported stays trusted by default). With the dialog unreachable and no approval, an HF source loads with trust_remote_code off, which fails closed rather than running unreviewed code.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
…scan The trust_remote_code consent gate covers one load-time RCE vector (a repo's auto_map Python). It does not cover the other: a malicious pickle inside a weight file (pytorch_model.bin, *.pkl, *.dat) deserializes during from_pretrained even with trust_remote_code False, so a repo with a normal config plus a poisoned pickle slips past the existing gate. Add a metadata-only malware gate that uses Hugging Face's own scan (picklescan + ClamAV), read via model_info(securityStatus=True).security_repo_status. It never downloads, opens, or unpickles the flagged files; it only reads the Hub's verdict and surfaces the flagged file names. New evaluate_file_security runs unconditionally (independent of trust_remote_code) in every load path (inference, training SFT/MLX, export), blocking the load when a file is flagged unsafe/suspicious/malicious. The /remote-code-scan preflight and the validate endpoint also report the result so the consent dialog opens as a hard block (no override) listing the flagged files, even for a repo with no custom code. Policy: hard block with no user override; fail open when the scan is unavailable (offline/unscanned) so legitimate loads are not broken; no first-party exemption (a poisoned pickle in a compromised trusted repo still blocks); local paths and GGUF are skipped (no Hub scan, non-pickle format). Blocking does not gate on scansDone, since that is often false for clean repos and a file already flagged unsafe is unsafe regardless. Adds test_file_security.py covering the block/allow/fail-open/skip matrix.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
…on all load paths
Fixes from a 10-reviewer pass on the model-fetching hardening:
- The remote-code scanner skipped tokenizer auto_map encoded as a [slow, fast]
list (transformers' standard tokenizer shape, e.g.
{"AutoTokenizer": ["owner/repo--tokenization_x.Slow", null]}). External
tokenizer code in that form was never fetched, scanned, or fingerprinted, so an
AutoTokenizer(trust_remote_code=True) load could run it. _auto_map_refs now
flattens string, list, and nested values. Adds a regression test.
- Compare-mode chat loads and background auto-load only gated on
requires_trust_remote_code, so a repo flagged unsafe by the Hub scan but with no
custom code skipped the hard-block dialog. Both now also gate on
requires_security_review, matching the main chat path.
- The /remote-code-scan and /validate routes collapsed a LoRA adapter to its base
before the malware scan, so unsafe files in the adapter repo itself were missed
in the pre-load review (the workers already scan both). Both routes now run the
file-security scan over the adapter and the base.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
Tighten the load-time security gates based on review: Consent gate - HIGH-severity auto_map code now requires explicit, per-version approval for every repo, including first-party unsloth/nvidia. The org is no longer a blanket bypass: a compromised first-party repo with HIGH code still warrants review. CRITICAL stays a hard block; clean code still loads after the consent prompt. - Fail closed when auto_map code is present but cannot be fully fetched or listed to scan (gated, offline, transient, or a repo-listing failure that could hide an imported helper). We cannot fingerprint code we cannot see, so this is a non-approvable block, retryable once the repo is reachable. - Scan auto_map from every config that can carry one (model, tokenizer, image and feature processor, processor, video processor), not just config.json and tokenizer_config.json, so a custom-processor model is not missed. The file list is the single source of truth in remote_code_scan and is pinned to the transformers filename constants by a guard test. - Distinguish a genuine 404 (config truly absent) from a transient error: only the latter forces a scan, so a repo with no config is correctly a no-op. Malware gate - Scan a remote repo even when its name ends in .gguf; only local paths skip the Hub scan, so a repo cannot dodge the scan by naming itself "*.gguf". - Correct the docstring: a file already flagged unsafe blocks regardless of scansDone; the only fail-open path is an unavailable scan. Coverage - Resolve a remote LoRA adapter's base model (not just local directories) so the base, where the code and weights actually execute, is scanned in validate, the scan route, and the training and export workers. - Gate the embedding training path (FastSentenceTransformer) with the malware and consent checks, matching the other load paths. Tests updated and added for each change.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
…-party models
Follow-up hardening from a second review pass + a broad live model matrix
(unsloth/* , nvidia/* , third-party, and the eicar malware repo).
Malware / unsafe-file gate
- Scope the block to the actual RCE vector: a root-level file in a code-executing
format. from_pretrained deserializes weight files at the repo ROOT, so a flag is
only a load-path pickle vector there. Two exclusions, because neither is loaded:
inert formats (safetensors is tensor-only, gguf is non-pickle, configs/text/
images) and files in subdirectories. This keeps eicar blocked (its *.pkl/*.dat/
eicar_test_file sit at the repo root) while no longer false-blocking legitimate
first-party repos: nvidia/Nemotron-H-8B-Base-8K ships root safetensors plus NeMo
pickle checkpoints under nemo/ that the loader never touches, and the Hub flags
both; the gate previously hard-blocked it.
- Unknown / future non-"safe" levels now fail closed (block) instead of being
silently allowed, so Hub schema drift cannot introduce a bypass; in-progress
("pending"/"scanning"/"error") levels stay non-blocking to avoid false blocks.
Consent gate
- Ignore a STALE own-repo auto_map target that is absent from the repo listing (an
older config pointing at a file the repo no longer ships) instead of failing the
whole repo closed as unscannable. The present .py are still fully scanned, which
is the stronger coverage, and a file that is not there cannot execute. This
unblocks first-party models like unsloth/PaddleOCR-VL (its tokenizer_config.json
names processing_ppocrvl.py while the repo ships processing_paddleocr_vl.py). A
referenced .py that IS present but cannot be fetched, and a repo-listing failure,
still fail closed.
Remote LoRA base resolution
- Distinguish a genuine 404 (not a LoRA / repo absent -> None) from a transient
error: the transient case is retried once, then logged as a WARNING (a missed
base is scanned by neither gate) rather than silently skipped.
Discard endpoint
- Treat .onnx and .ckpt as weights so a repo whose only heavy artifact is one of
those is never eligible for the declined-download purge.
Tests added for each: load-path scoping (safetensors/subdir/Nemotron-H shapes,
unknown-level fail-closed, pending non-block), stale own-repo auto_map ref, remote
LoRA transient retry, and the empty-config-list (all-404 -> []) semantics.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8aaefde20f
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| else: | ||
| blocked, reason = False, "allowed: no high-risk patterns" |
There was a problem hiding this comment.
Require fingerprints for clean custom code too
When an auto_map repo scans clean, this branch allows the load without checking approved_fingerprint. In rollback paths or any caller replaying a stale/null approval, a previously approved model whose repo code changed but still avoids the static findings can execute without re-prompting, even though the consent flow is meant to pin approval to the scanned fingerprint. Require the fingerprint to match for all scanned remote code, not only MEDIUM/HIGH findings.
Useful? React with 👍 / 👎.
| error = resp.get("error", "Failed to load model") | ||
| # The load worker reports failure under "message" (the consent | ||
| # gate included); fall back to "error" then a generic string. | ||
| error = resp.get("message") or resp.get("error") or "Failed to load model" |
There was a problem hiding this comment.
Preserve the worker's security-block payload
When the subprocess backstop blocks a load after the frontend preflight, for example because the repo code changed between scan and load or an API caller skipped the UI, the worker response includes error_kind plus remote_code/security details with the current fingerprint. Collapsing that response to a plain exception string makes /api/inference/load return only a generic 500-style error, so clients cannot render the non-approvable block or re-prompt with the new fingerprint from the backend's authoritative scan. Propagate the structured security payload instead of discarding it here.
Useful? React with 👍 / 👎.
| "config.json", | ||
| "tokenizer_config.json", | ||
| "preprocessor_config.json", | ||
| "processor_config.json", | ||
| "video_preprocessor_config.json", |
There was a problem hiding this comment.
Include LLM subfolder configs in the remote-code gate
For Spark-TTS/BiCodec loads, the training and inference paths download the repo and then call FastModel.from_pretrained on the LLM subdirectory while forwarding trust_remote_code; however this config list only checks root-level files. If LLM/config.json declares auto_map and a caller sets trust_remote_code=True, _config_has_auto_map reports no remote code for the repo root, so the subfolder's Python executes without scan or fingerprint approval. Include the load-subdirectory configs or run consent on the actual from_pretrained path.
Useful? React with 👍 / 👎.
…clined repos Three follow-on gaps from the combined adapter+base consent work: - validate_model resolved requires_trust_remote_code from the base alone, so a LoRA adapter that ships its OWN auto_map code (with a plain base) was reported as not needing trust_remote_code and the consent dialog never opened. It now checks the [adapter, base] target set, matching the scan route and the workers (which already gate both) and the security review already running over both. - The already-loaded, loaded, and status responses for a selected GGUF reported requires_trust_remote_code from the model's YAML default. A GGUF loads through llama.cpp, which never executes the repo's auto_map Python, so the requirement is inert for that load. They now report False, matching validate_model (which already skips both gates for GGUF) so a status refresh cannot flip the flag back on. - The remote-code scan downloads both the adapter's and the base's config, but created_by_scan tracked only the primary, so a base the scan was first to pull into the cache was left on disk when the user declined. The scan now reports scan_created_repos (every repo it newly cached) and the decline cleanup purges each; created_by_scan stays for older clients. The frontend falls back to the primary flag when the list is absent.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 337d58af60
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| for _target in security_targets: | ||
| try: | ||
| if (not is_local_path(_target)) and not _repo_in_any_hf_cache(_target): | ||
| scan_created_repos.append(_target) |
There was a problem hiding this comment.
Track external auto_map repos for decline cleanup
When a model's auto_map references code in another Hub repo (owner/repo--module.Class), repo_remote_code_files() downloads that external repo during the preflight scan, but this loop only records the primary adapter/base security_targets for later cleanup. If the user declines the dialog, the frontend only purges scan_created_repos, so scan-downloaded external Python is left in the HF cache; the fresh evidence is the new _add_external_refs path that downloads repos outside security_targets. Include those external repos in the created-by-scan list or compute cleanup from a before/after cache diff.
Useful? React with 👍 / 👎.
| from utils.paths import is_local_path | ||
| if is_local_path(name): | ||
| return True |
There was a problem hiding this comment.
Check that local .gguf references are files
For a local directory whose name ends in .gguf, is_local_path(name) is true here and the consent gate returns False before reading config.json, even though detect_gguf_model() explicitly treats *.gguf directories as directories and only classifies them as GGUF if they contain a real GGUF file. A transformer model stored in a directory like /tmp/model.gguf with auto_map can therefore be loaded with trust_remote_code=True without any scan or fingerprint approval. Require the path to be a file, or use the resolved ModelConfig.is_gguf load mode, before bypassing the gate.
Useful? React with 👍 / 👎.
| identifier, | ||
| type(last_exc).__name__ if last_exc else "unknown", | ||
| ) | ||
| return None |
There was a problem hiding this comment.
Fail closed when LoRA base resolution is inconclusive
When a remote LoRA adapter's adapter_config.json fetch hits a transient error during the export/training security preflight, returning None makes callers scan only the adapter. The later from_pretrained call can retry successfully, read that same adapter config, and load the base model, so a poisoned base pickle or base auto_map code can run without being included in the malware/consent targets. Propagate an inconclusive result and block instead; only a genuine missing adapter config should skip the base.
Useful? React with 👍 / 👎.
| return False | ||
| # The import closure the loader can execute = every .py in the external repo, | ||
| # plus any explicitly-referenced entry file (in case listing is incomplete). | ||
| wanted = {f for f in repo_files if f.endswith(".py")} | set(entry_files) |
There was a problem hiding this comment.
Drop stale external auto_map entry paths
For an external auto_map that names a submodule such as evil/repo--pkg.modeling.Evil, _auto_map_refs records pkg.modeling.py, while the Hub file is normally pkg/modeling.py. Because wanted unconditionally unions that derived entry with the listed .py files, the scanner will already fetch and scan pkg/modeling.py from the listing, then try to download the nonexistent pkg.modeling.py and hard-block the load as unscannable. Mirror the own-repo stale-ref handling here by ignoring derived external entries absent from repo_files instead of failing after the real files have been scanned.
Useful? React with 👍 / 👎.
…n consent pins Six follow-on hardening fixes from a fresh review pass over the gate: - The malware gate scanned the literal "Spark-TTS-0.5B/LLM" alias, but the trainer downloads it as unsloth/Spark-TTS-0.5B and loads LLM/, so the alias 404'd and failed open, missing a flagged LLM/ pickle. evaluate_file_security now resolves the alias to the repo the loader fetches and scans LLM/ as a load root. - security_load_subdirs relied only on tokenizer detection, which fails on an unresolved alias or offline; it now also honors the Studio YAML audio_type default, so a BiCodec LLM/ load root is not missed. - The remote-code scan downloads external auto_map repos (owner/name--module.Class), but the decline cleanup tracked only the model/adapter/base, leaving the external untrusted code cached. The scan now enumerates external auto_map repos and reports the ones it created in scan_created_repos, so a decline purges them too. - External auto_map refs failed the whole load closed on a stale or mis-derived dotted ref (sub.mod.py vs the real sub/mod.py) even though the actual file was present and scanned. They now drop such refs when the repo listing is real, exactly like the own-repo path; an empty/incomplete listing still fetches and fails closed. - The combined consent fingerprint keyed code by the raw target string, so the scan endpoint's canonicalized casing and a worker's raw user input produced different pins for identical code, rejecting a valid approval. Hub repo ids are now folded to lowercase in the key (local paths stay case-sensitive), so the pin tracks the code. - Export threaded hf_token into the weight load but not into detect_audio_type / is_vision_model, so a gated multimodal base 404'd in detection and fell through to the text loader. Both probes now use the same token.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 37ffed742c
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| : reloadingSameModel && supportsReasoning | ||
| ? stateBeforeUnload.reasoningEnabled | ||
| : reasoningDefault; | ||
| rememberApprovedRemoteCode(modelId, approvedRemoteCodeFingerprint); |
There was a problem hiding this comment.
Store approvals under the loaded checkpoint id
When the backend canonicalizes the loaded id (for example a shorthand/case-variant request that later refreshes params.checkpoint from status.model_identifier), this stores the approval only under the original modelId, while rollback looks up approvedRemoteCodeFingerprints.get(previousCheckpoint). After a subsequent model switch fails, restoring an already-approved HIGH/MEDIUM custom-code model can therefore resend trust_remote_code=true with a null fingerprint and be rejected by the worker; store the fingerprint under the response/status checkpoint id as well as the request id.
Useful? React with 👍 / 👎.
…ites The /check-vision endpoint classified a model without the hf_token, so a gated or private vision model 404'd in the probe and was reported as a plain text model -- the same dropped-token shape as the export probes, at a sibling site. It now passes the token like the neighboring /check-embedding endpoint. Add deterministic consistency guards (tests/test_security_gate_consistency.py) that enumerate the gate's parallel sites mechanically instead of relying on a review to spot a missed sibling: every is_vision_model / is_embedding_model / detect_audio_type caller under routes/ and core/ must thread the token, every GGUF response must report trust_remote_code via the resolver or False (never the raw YAML default), and every load worker that runs the malware or consent gate must resolve the LoRA base. A new site that drops the token or mis-reports the requirement now fails CI directly.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
Three fixes from the confirmatory review, one a regression from the previous round: - _load_scan_target rewrote EVERY remote repo ending in "/LLM" to unsloth/<parent>, so a real third-party repo named "<owner>/LLM" was scanned as unsloth/<owner> while the loader still fetched the real repo -- a fail-open hole introduced when the Spark-TTS alias handling was added. It now rewrites only a registry-known bicodec alias; every other "/LLM" repo is scanned as itself. - detect_audio_type cached results under the bare model name, so an unauthenticated probe of a gated/private repo cached None and poisoned a later authenticated call with the token. The cache is now keyed by (normalized_name, token_fingerprint), matching the vision cache. - The training fallback /check-vision call dropped the hf_token, misclassifying a gated/private VLM when the config endpoint failed. It now passes the token, like the getModelConfig call it falls back from; checkEmbeddingModel takes the token too. Extend the consistency guards: every capability cache must be keyed by a tuple including the token, so a cache re-declared as Dict[str, ...] fails CI.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
The remote-code scanner scans every .py in a repo once an auto_map exists, not just the auto_map entry's static import closure. This is intentional: the entry module can reach a sibling via an absolute import, importlib, or exec, none of which a static relative-import closure follows, so closure-only scanning would be a real bypass of a load-time RCE gate. The broad scan never under-scans; the cost is that an unrelated benign script can over-block, which is the safe failure direction (HIGH stays approvable; only CRITICAL hard-blocks). Spell this out at both the local and remote scan sites so the choice reads as deliberate, and add a test asserting an unrelated, never-imported .py is still scanned -- so a future narrowing to the static closure fails CI.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
scan_model_remote_code probed the created-by-scan state AFTER resolving the base, but get_base_model_from_lora_identifier downloads a remote adapter's own adapter_config.json, so the adapter looked already-cached and was dropped from scan_created_repos. On decline the adapter -- including the auto_map .py the preflight fetched -- was left on disk, defeating the "untrusted code is not left on disk" guarantee for the adapter itself. Snapshot the primary's cache state BEFORE base resolution and use it when marking the adapter scan-created; on any probe error treat it as pre-existing so a decline never deletes it. The base and external repos are unaffected (their configs are not downloaded before their own probe). Add a test that models the mid-scan download side effect, which the prior static-stub tests did not.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
Switching the training model from an approved custom-code model to a clean one kept the previous model's trust_remote_code=true and approved fingerprint in the store: setSelectedModel reset visionImageSize on a true switch but not the remote-code approval. The clean model then trained with trust_remote_code=true, which bypasses the compiler and disables fused cross-entropy. Reset trustRemoteCode and approvedRemoteCodeFingerprint on a true model switch. The new model's own YAML default is re-applied by loadAndApplyModelDefaults, and a custom-code model still re-opens the consent dialog before training starts, so the only change is that a clean model no longer inherits a stale approval.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
Condense the explanatory comments and docstrings introduced across the trust_remote_code consent gate, the malware/unsafe-file gate, the remote-code scanner, the load workers, the model routes, and the security frontend into fewer, tighter lines while preserving every security rationale (fail-open vs fail-closed direction, the deliberate broad-scan anti-bypass note, the empty-vs-unscannable distinction, stale-ref handling, and the alias-rewrite spoof guard). Comments and docstrings only. No code, logic, identifiers, or test behaviour changed; verified comment-only via the AST/TypeScript checker (40/40), with the backend test suite and frontend tsc green.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
detect_audio_type cached _detect_audio_from_tokenizer's result unconditionally, so a transient read failure (network error or 5xx, returned as None) poisoned the cache and the later successful probe never ran. Mirror the vision cache: _detect_audio_from_tokenizer now returns (audio_type, definitive) and the caller caches only definitive results. A read that succeeds with no audio tokens, or clean 404s for every tokenizer path, stays a cacheable None; only a genuine transient failure (connection error, timeout, 5xx, malformed body) skips the cache so the next call retries.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
Summary
Loading a model with
trust_remote_coderuns whatever Python the repo points to from itsconfig.jsonauto_map, and that code runs the momentAutoConfig/from_pretrainedtouches the repo, before any generation. Studio also reached forAutoConfigduring routine, automatic probes (capability detection, GPU/VRAM estimation, metadata lookups) that fire just from selecting a model, so a repo's code could run without the user ever asking to load it.This locks that down on two fronts.
Never execute repo code on automatic probes
Every automatic probe now reads
config.jsondeclaratively instead of going throughAutoConfig:utils/models/model_config.py) defaultstrust_remote_code=False; anyAutoConfiguse for newer-transformers checks runs with remote code disabled or inside an isolated subprocess.utils/hardware/hardware.py) reads the rawconfig.jsonand exposes it as an attribute namespace, so the estimate that runs on model selection never executes repo code.routes/models.py) resolvesrequires_trust_remote_codefrom the raw config, not by importing the model.Consent gate before any trust_remote_code load
When a load genuinely needs
trust_remote_code, a gate scans the repo'sauto_mapPython first and surfaces the findings before anything executes:config.jsonand scans the.py, and never loads the model.The gate runs in all three load paths (training, chat, export), and the frontend shows one shared consent dialog that lists each finding with the flagged line shown in context (line numbers, the surrounding code, and the matched span highlighted). The per-worker gate stays as a backstop and only proceeds when the supplied fingerprint matches the freshly scanned code.
The remote-code scanner is sourced from
scripts/scan_packages.pyso the load-time gate and the CI package scanner share one ruleset, with a small model-context strictness layer formodeling_*.py.Tests
studio/backend/tests/test_consent_gate.py,test_load_consent.py,test_capability_detection.py,test_verify_a.py(capability detection never executesauto_map),test_verify_c.py(trusted-org + scan), plus the existingtest_transformers_version.pyandtest_safetensors_capability_advertise.py: all green.tsctypecheck and production build pass.