Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: stop rejecting provider API keys longer than 190 bytes (#10421)
Long Yixinge0f84159eeb4
diff --git a/studio/backend/core/inference/key_exchange.py b/studio/backend/core/inference/key_exchange.pyindex 15ef30102ee..eb5b90bf7cd 100644--- a/studio/backend/core/inference/key_exchange.py+++ b/studio/backend/core/inference/key_exchange.py@@ -11,6 +11,9 @@ providers.The key pair is generated at server startup, lives only in memory, and isregenerated on each restart. The frontend fetches the public key viaGET /api/providers/public-key on load.++A per-request AES-256-GCM key carries the secret and RSA-OAEP wraps only that+key: encrypting the secret under RSA directly would cap it at 190 bytes."""import base64@@ -18,10 +21,16 @@ import hashlibimport loggingfrom cryptography.hazmat.primitives.asymmetric import rsa, padding+from cryptography.hazmat.primitives.ciphers.aead import AESGCMfrom cryptography.hazmat.primitives import serialization, hasheslogger = logging.getLogger(__name__)+_ENVELOPE_VERSION = "v1"+_ENVELOPE_PARTS = 4+# Pins an envelope to this protocol and version, as the at-rest secrets do.+_ENVELOPE_AAD = b"unsloth-studio-provider-key-v1"+_private_key: rsa.RSAPrivateKey | None = None_public_key_pem: str | None = None_public_key_fingerprint: str | None = None@@ -73,33 +82,9 @@ def get_public_key_pem() -> str:return _public_key_pem-def decrypt_api_key(encrypted_b64: str) -> str:- """- Decrypt an API key that was encrypted with the public key.-- Args:- encrypted_b64: Base64-encoded RSA-OAEP ciphertext.-- Returns:- The plaintext API key string.- """- if _private_key is None:- raise RuntimeError("Key pair not initialized. Call init_key_pair() first.")-- try:- ciphertext = base64.b64decode(encrypted_b64)- except Exception as exc:- logger.warning(- "decrypt_api_key: base64 decode failed (input_len=%d, fingerprint=%s): %s: %s",- len(encrypted_b64),- _public_key_fingerprint,- type(exc).__name__,- exc,- )- raise-+def _unwrap_oaep(ciphertext: bytes, *, what: str) -> bytes:try:- plaintext = _private_key.decrypt(+ return _private_key.decrypt(ciphertext,padding.OAEP(mgf = padding.MGF1(algorithm = hashes.SHA256()),@@ -110,8 +95,9 @@ def decrypt_api_key(encrypted_b64: str) -> str:except Exception as exc:# RSA-2048 ciphertext is exactly 256 bytes; log state to separate key mismatch from paddinglogger.warning(- "decrypt_api_key: RSA decrypt failed (ciphertext_len=%d, expected=256, "+ "decrypt_api_key: RSA decrypt failed (%s, ciphertext_len=%d, expected=256, ""fingerprint=%s, exc=%s): %s",+ what,len(ciphertext),_public_key_fingerprint,type(exc).__name__,@@ -119,4 +105,66 @@ def decrypt_api_key(encrypted_b64: str) -> str:)raise++def _b64decode_part(value: str, *, what: str, validate: bool) -> bytes:+ try:+ return base64.b64decode(value, validate = validate)+ except Exception as exc:+ logger.warning(+ "decrypt_api_key: base64 decode failed (%s, input_len=%d, fingerprint=%s): %s: %s",+ what,+ len(value),+ _public_key_fingerprint,+ type(exc).__name__,+ exc,+ )+ raise+++def decrypt_api_key(encrypted_b64: str) -> str:+ """Decrypt an API key encrypted with the public key.++ Accepts ``v1.<wrapped AES key>.<nonce>.<ciphertext||tag>``, each part base64, and the+ bare RSA-OAEP ciphertext frontend builds predating the envelope send. Base64 has no+ ``.``, so the two can never be confused.+ """+ if _private_key is None:+ raise RuntimeError("Key pair not initialized. Call init_key_pair() first.")++ if "." in encrypted_b64:+ parts = encrypted_b64.split(".")+ if parts[0] != _ENVELOPE_VERSION or len(parts) != _ENVELOPE_PARTS:+ logger.warning(+ "decrypt_api_key: malformed envelope (version=%r, parts=%d, expected %r/%d, "+ "fingerprint=%s)",+ parts[0][:8],+ len(parts),+ _ENVELOPE_VERSION,+ _ENVELOPE_PARTS,+ _public_key_fingerprint,+ )+ raise ValueError("Unsupported encrypted API key envelope.")+ wrapped_key = _b64decode_part(parts[1], what = "wrapped_key", validate = True)+ nonce = _b64decode_part(parts[2], what = "nonce", validate = True)+ ciphertext = _b64decode_part(parts[3], what = "ciphertext", validate = True)+ aes_key = _unwrap_oaep(wrapped_key, what = "wrapped_key")+ try:+ plaintext = AESGCM(aes_key).decrypt(nonce, ciphertext, _ENVELOPE_AAD)+ except Exception as exc:+ logger.warning(+ "decrypt_api_key: AES-GCM decrypt failed (nonce_len=%d, ciphertext_len=%d, "+ "fingerprint=%s, exc=%s): %s",+ len(nonce),+ len(ciphertext),+ _public_key_fingerprint,+ type(exc).__name__,+ exc,+ )+ raise+ else:+ # Lenient, as this path was before the envelope: tightening it could reject a key+ # that works today.+ legacy_ciphertext = _b64decode_part(encrypted_b64, what = "legacy", validate = False)+ plaintext = _unwrap_oaep(legacy_ciphertext, what = "legacy")+return plaintext.decode("utf-8")diff --git a/studio/backend/tests/test_credential_secrets.py b/studio/backend/tests/test_credential_secrets.pyindex 70287ce2370..8b5eea78ddb 100644--- a/studio/backend/tests/test_credential_secrets.py+++ b/studio/backend/tests/test_credential_secrets.py@@ -4,6 +4,7 @@from __future__ import annotations+import base64import osimport subprocessimport sys@@ -12,8 +13,14 @@ import sqlite3from concurrent.futures import ThreadPoolExecutorimport pytest+from cryptography.exceptions import InvalidTag+from cryptography.hazmat.primitives import hashes+from cryptography.hazmat.primitives.asymmetric import padding+from cryptography.hazmat.primitives.ciphers.aead import AESGCMfrom auth import storage as auth_storage+from core.inference import key_exchange+from core.inference.key_exchange import decrypt_api_key, init_key_pairfrom storage import credential_secrets@@ -224,3 +231,117 @@ assert seen["api_key"] == "sk_restart"check = True,timeout = 30,)+++# ── API key transport envelope ──────────────────────────────────────+#+# Keys reach the backend as "v1.<RSA-wrapped AES key>.<nonce>.<ciphertext||tag>", each part+# base64. Builds predating the envelope send bare RSA ciphertext instead.++# The reported OVH key length, and the last length bare RSA-OAEP-SHA256 could carry.+OVH_KEY_LENGTH = 238+LEGACY_MAX_LENGTH = 190++# Spelled out rather than imported: this is the contract encryptProviderApiKey writes, so+# reading it from the module would let both sides drift together.+ENVELOPE_VERSION = "v1"+ENVELOPE_AAD = b"unsloth-studio-provider-key-v1"++OAEP = padding.OAEP(+ mgf = padding.MGF1(algorithm = hashes.SHA256()),+ algorithm = hashes.SHA256(),+ label = None,+)++[email protected](scope = "module", autouse = True)+def key_pair():+ init_key_pair()+++def _b64(raw: bytes) -> str:+ return base64.b64encode(raw).decode("utf-8")+++def encrypt_envelope(+ plaintext: str,+ *,+ aad: bytes = ENVELOPE_AAD,+ nonce: bytes = b"\x00" * 12,+ version: str = ENVELOPE_VERSION,+) -> str:+ """The frontend half of the envelope, mirroring encryptProviderApiKey."""+ aes_key = b"\x11" * 32+ wrapped = key_exchange._private_key.public_key().encrypt(aes_key, OAEP)+ sealed = AESGCM(aes_key).encrypt(nonce, plaintext.encode("utf-8"), aad)+ return ".".join([version, _b64(wrapped), _b64(nonce), _b64(sealed)])+++def encrypt_legacy(plaintext: str) -> str:+ """A build predating the envelope: bare RSA-OAEP ciphertext, base64."""+ return _b64(key_exchange._private_key.public_key().encrypt(plaintext.encode("utf-8"), OAEP))+++ "length",+ [1, LEGACY_MAX_LENGTH - 1, LEGACY_MAX_LENGTH, LEGACY_MAX_LENGTH + 1, OVH_KEY_LENGTH, 4096],+)+def test_envelope_round_trips_at_any_length(length):+ api_key = "k" + "x" * (length - 1)+ assert decrypt_api_key(encrypt_envelope(api_key)) == api_key+++def test_envelope_round_trips_a_non_ascii_key():+ api_key = "sk-café-日本語-🔑-Ünïcödé"+ assert decrypt_api_key(encrypt_envelope(api_key)) == api_key+++def test_the_envelope_carries_a_key_bare_rsa_cannot():+ api_key = "k" * OVH_KEY_LENGTH+ with pytest.raises(ValueError):+ encrypt_legacy(api_key)+ assert decrypt_api_key(encrypt_envelope(api_key)) == api_key+++def test_legacy_bare_rsa_ciphertext_still_decrypts():+ assert decrypt_api_key(encrypt_legacy("sk-legacy")) == "sk-legacy"+++def test_a_tampered_ciphertext_is_rejected():+ parts = encrypt_envelope("sk-tamper").split(".")+ sealed = bytearray(base64.b64decode(parts[3]))+ sealed[0] ^= 0x01+ parts[3] = _b64(bytes(sealed))+ with pytest.raises(InvalidTag):+ decrypt_api_key(".".join(parts))+++def test_a_different_nonce_is_rejected():+ parts = encrypt_envelope("sk-nonce").split(".")+ parts[2] = _b64(b"\x09" * 12)+ with pytest.raises(InvalidTag):+ decrypt_api_key(".".join(parts))+++def test_an_envelope_sealed_under_other_associated_data_is_rejected():+ with pytest.raises(InvalidTag):+ decrypt_api_key(encrypt_envelope("sk-aad", aad = b"some-other-protocol"))++[email protected]("parts", [2, 3, 5])+def test_a_v1_envelope_with_the_wrong_part_count_is_rejected(parts):+ with pytest.raises(ValueError):+ decrypt_api_key(".".join(["v1"] + ["QUJD"] * (parts - 1)))+++def test_envelope_parts_are_decoded_strictly():+ """Whitespace a permissive decoder would drop, restoring an otherwise valid envelope."""+ parts = encrypt_envelope("sk-b64").split(".")+ parts[3] = parts[3][:4] + "\n" + parts[3][4:]+ with pytest.raises(ValueError):+ decrypt_api_key(".".join(parts))+++def test_an_unknown_version_is_rejected_rather_than_read_as_legacy():+ with pytest.raises(ValueError, match = "Unsupported"):+ decrypt_api_key(encrypt_envelope("sk-future", version = "v2"))diff --git a/studio/frontend/src/features/chat/api/providers-api.ts b/studio/frontend/src/features/chat/api/providers-api.tsindex e5d474117ac..e2d0691df78 100644--- a/studio/frontend/src/features/chat/api/providers-api.ts+++ b/studio/frontend/src/features/chat/api/providers-api.ts@@ -124,16 +124,49 @@ async function importProviderPublicKey(return forgeKey;}+const ENVELOPE_VERSION = "v1";+/** Pins an envelope to this protocol and version; the backend checks the same bytes. */+const ENVELOPE_AAD = "unsloth-studio-provider-key-v1";+const AES_KEY_BYTES = 32;+const NONCE_BYTES = 12;++function randomBinaryString(byteLength: number): string {+ const bytes = new Uint8Array(byteLength);+ crypto.getRandomValues(bytes);+ return String.fromCharCode(...bytes);+}++/**+ * Produce `v1.<wrapped AES key>.<nonce>.<ciphertext||tag>`, each part base64. RSA-OAEP wraps+ * only the 32-byte content key: encrypting the API key itself would cap it at 190 bytes.+ */export async function encryptProviderApiKey(plaintextApiKey: string,forceRefresh = false,): Promise<string> {const key = await importProviderPublicKey(forceRefresh);- const encrypted = key.encrypt(plaintextApiKey, "RSA-OAEP", {+ const aesKey = randomBinaryString(AES_KEY_BYTES);+ const nonce = randomBinaryString(NONCE_BYTES);++ const cipher = forge.cipher.createCipher("AES-GCM", aesKey);+ cipher.start({ iv: nonce, additionalData: ENVELOPE_AAD, tagLength: 128 });+ // forge ciphers take bytes, so a non-ASCII key would otherwise lose all but the low byte+ // of each UTF-16 code unit.+ cipher.update(forge.util.createBuffer(forge.util.encodeUtf8(plaintextApiKey)));+ if (!cipher.finish()) {+ throw new Error("Failed to encrypt API key.");+ }++ const wrappedKey = key.encrypt(aesKey, "RSA-OAEP", {md: forge.md.sha256.create(),mgf1: { md: forge.md.sha256.create() },});- return forge.util.encode64(encrypted);+ return [+ ENVELOPE_VERSION,+ forge.util.encode64(wrappedKey),+ forge.util.encode64(nonce),+ forge.util.encode64(cipher.output.getBytes() + cipher.mode.tag.getBytes()),+ ].join(".");}export async function listProviderRegistry(): Promise<ProviderRegistryEntry[]> {diff --git a/studio/frontend/tests/credential-persistence.test.ts b/studio/frontend/tests/credential-persistence.test.tsindex 2a35ffa2696..8a73dc3c801 100644--- a/studio/frontend/tests/credential-persistence.test.ts+++ b/studio/frontend/tests/credential-persistence.test.ts@@ -5,6 +5,7 @@ import assert from "node:assert/strict";import { readFileSync } from "node:fs";import test from "node:test";+import forge from "node-forge";import type { ProviderConfig } from "../src/features/chat/api/providers-api.ts";@@ -12,6 +13,7 @@ import {installLocalStorageFake,registerStoreStubResolver,} from "./helpers/kit.ts";+import { loadWithStubs } from "./helpers/module-stubs.ts";registerStoreStubResolver();@@ -755,3 +757,120 @@ test("credential gate follows authentication session transitions", () => {);});+++// ── API key transport envelope ──────────────────────────────────────+//+// encryptProviderApiKey wraps a per-request AES key under RSA rather than encrypting the API+// key itself, so key length stops being bounded by the modulus: RSA-2048/OAEP-SHA256 caps a+// directly encrypted key at 190 bytes, and providers issue longer ones.++type EncryptionModule = {+ encryptProviderApiKey: (plaintextApiKey: string, forceRefresh?: boolean) => Promise<string>;+ clearProviderPublicKeyCache: () => void;+};++// Spelled out rather than imported: this is the contract decrypt_api_key reads, so taking it+// from the module under test would let both sides drift together.+const ENVELOPE_AAD = "unsloth-studio-provider-key-v1";+const TAG_BYTES = 16;+// The backend decodes with validate=True, which forge's decode64 does not model.+const STRICT_BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;+const OAEP = { md: forge.md.sha256.create(), mgf1: { md: forge.md.sha256.create() } };++const keypair = forge.pki.rsa.generateKeyPair({ bits: 2048, e: 0x10001 });+const publicKeyPem = forge.pki.publicKeyToPem(keypair.publicKey);++function encryptionHarness() {+ let fetches = 0;+ const module = loadWithStubs<EncryptionModule>(+ new URL("../src/features/chat/api/providers-api.ts", import.meta.url),+ {+ // transpileModule runs without esModuleInterop, so a default import reads .default+ "node-forge": { default: forge },+ "@/features/auth/api": {+ authFetch: async () => {+ fetches += 1;+ return { ok: true, status: 200, json: async () => ({ public_key: publicKeyPem }) };+ },+ },+ "@/lib/format-fastapi-error": { formatFastApiDetail: () => null },+ },+ );+ return { module, publicKeyFetches: () => fetches };+}++/** The backend half of the envelope, so a round-trip proves the wire format and not itself. */+function openEnvelope(envelope: string): { apiKey: string; aesKey: string } {+ const parts = envelope.split(".");+ assert.equal(parts.length, 4);+ assert.equal(parts[0], "v1");+ for (const part of parts.slice(1)) {+ assert.match(part, STRICT_BASE64);+ }+ const [wrappedKey, nonce, sealed] = parts.slice(1).map((part) => forge.util.decode64(part));+ const aesKey = keypair.privateKey.decrypt(wrappedKey, "RSA-OAEP", OAEP);+ assert.equal(aesKey.length, 32);+ assert.equal(nonce.length, 12);++ const decipher = forge.cipher.createDecipher("AES-GCM", aesKey);+ decipher.start({+ iv: nonce,+ additionalData: ENVELOPE_AAD,+ tagLength: 128,+ tag: forge.util.createBuffer(sealed.slice(-TAG_BYTES)),+ });+ decipher.update(forge.util.createBuffer(sealed.slice(0, -TAG_BYTES)));+ assert.ok(decipher.finish(), "AES-GCM tag did not verify");+ return { apiKey: forge.util.decodeUtf8(decipher.output.getBytes()), aesKey };+}++test("api keys round-trip at every length, including past the old RSA ceiling", async () => {+ const { module } = encryptionHarness();+ // 190 is the last length RSA-OAEP-SHA256 could carry directly; 238 is the reported OVH key.+ for (const length of [1, 189, 190, 191, 238, 4096]) {+ const apiKey = `k${"x".repeat(length - 1)}`;+ assert.equal(openEnvelope(await module.encryptProviderApiKey(apiKey)).apiKey, apiKey);+ }+});++test("a non-ascii api key survives the round-trip", async () => {+ const { module } = encryptionHarness();+ const apiKey = "sk-café-日本語-🔑-Ünïcödé";+ assert.equal(openEnvelope(await module.encryptProviderApiKey(apiKey)).apiKey, apiKey);+});++test("each envelope carries fresh key material", async () => {+ const { module } = encryptionHarness();+ const [first, second] = await Promise.all([+ module.encryptProviderApiKey("sk-same"),+ module.encryptProviderApiKey("sk-same"),+ ]);+ assert.notEqual(first.split(".")[2], second.split(".")[2], "nonce was reused");+ // RSA-OAEP is randomized, so the wrapped-key part differs even for one constant AES key.+ const opened = [openEnvelope(first), openEnvelope(second)];+ assert.notEqual(opened[0].aesKey, opened[1].aesKey, "AES content key was reused");+ for (const { apiKey } of opened) {+ assert.equal(apiKey, "sk-same");+ }+});++test("a tampered envelope fails the tag instead of yielding plaintext", async () => {+ const { module } = encryptionHarness();+ const parts = (await module.encryptProviderApiKey("sk-tamper")).split(".");+ const sealed = forge.util.decode64(parts[3]);+ parts[3] = forge.util.encode64(+ String.fromCharCode(sealed.charCodeAt(0) ^ 0x01) + sealed.slice(1),+ );+ assert.throws(() => openEnvelope(parts.join(".")), /tag did not verify/);+});++test("the public key is fetched once and reused until the cache is cleared", async () => {+ const { module, publicKeyFetches } = encryptionHarness();+ await module.encryptProviderApiKey("sk-a");+ await module.encryptProviderApiKey("sk-b");+ assert.equal(publicKeyFetches(), 1);+ module.clearProviderPublicKeyCache();+ await module.encryptProviderApiKey("sk-c");+ assert.equal(publicKeyFetches(), 2);+});