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: read the saved credential and its presence in one query (#11420)
Daniel Han64e4d52d4886
diff --git a/studio/backend/hub/utils/hf_tokens.py b/studio/backend/hub/utils/hf_tokens.pyindex ee2fd909ada..baf17190987 100644--- a/studio/backend/hub/utils/hf_tokens.py+++ b/studio/backend/hub/utils/hf_tokens.py@@ -367,17 +367,15 @@ def _saved_studio_hf_token() -> "tuple[bool, Optional[str]]":from storage import credential_secretsexcept Exception:return (False, None)+ # Value and presence from ONE read: `get_secret` answers None for an absent row AND for an+ # undecryptable one, and conflating them is fail-open, but asking the store twice was two+ # sqlite connections on a path every read of a cached repo goes through.try:- token = credential_secrets.get_hf_token()+ token, stored = credential_secrets.get_hf_token_with_presence()except Exception:return (False, None)if isinstance(token, str) and token.strip():return (True, token.strip())- # `get_secret` returns None for an absent row AND an undecryptable one; conflating is fail-open.- try:- stored = credential_secrets.hf_token_row_exists()- except Exception:- return (False, None)if stored:return (False, None)return (True, None)diff --git a/studio/backend/storage/credential_secrets.py b/studio/backend/storage/credential_secrets.pyindex d80efcf0c34..75736d87bc2 100644--- a/studio/backend/storage/credential_secrets.py+++ b/studio/backend/storage/credential_secrets.py@@ -165,8 +165,13 @@ def insert_secret_if_absent(credential_kind: str, scope_id: str, plaintext: str)conn.close()-def get_secret(credential_kind: str, scope_id: str) -> Optional[str]:- """Return a decrypted credential, or ``None`` if absent or unreadable."""+def get_secret_with_presence(credential_kind: str, scope_id: str) -> "tuple[Optional[str], bool]":+ """The decrypted credential, and whether a row is STORED at all, from ONE read.++ Asking `get_secret` and then `secret_row_exists` is two connections for one question, and+ the cache-read gate in hub/utils/hf_tokens.py asks it on every read of a cached repo. The+ two answers must still be told apart: absent authorizes, unreadable must not.+ """conn = get_connection()try:row = conn.execute(@@ -179,21 +184,28 @@ def get_secret(credential_kind: str, scope_id: str) -> Optional[str]:).fetchone()finally:conn.close()- if row is None or row["format_version"] != _FORMAT_VERSION:- return None+ if row is None:+ return (None, False)+ if row["format_version"] != _FORMAT_VERSION:+ return (None, True)try:plaintext = AESGCM(get_or_create_credential_encryption_key()).decrypt(bytes(row["nonce"]),bytes(row["ciphertext"]),_associated_data(credential_kind, scope_id),)- return plaintext.decode("utf-8")+ return (plaintext.decode("utf-8"), True)except Exception:logger.warning("Saved credential is unreadable; re-entry is required (kind=%s)",credential_kind,)- return None+ return (None, True)+++def get_secret(credential_kind: str, scope_id: str) -> Optional[str]:+ """Return a decrypted credential, or ``None`` if absent or unreadable."""+ return get_secret_with_presence(credential_kind, scope_id)[0]def has_secret(credential_kind: str, scope_id: str) -> bool:@@ -245,6 +257,11 @@ def get_hf_token() -> Optional[str]:return get_secret(HF_TOKEN_KIND, HF_TOKEN_SCOPE)+def get_hf_token_with_presence() -> "tuple[Optional[str], bool]":+ """The saved HF token and whether one is stored at all. See `get_secret_with_presence`."""+ return get_secret_with_presence(HF_TOKEN_KIND, HF_TOKEN_SCOPE)++def hf_token_row_exists() -> bool:"""Whether an HF token is saved, readable or not. See `secret_row_exists`."""return secret_row_exists(HF_TOKEN_KIND, HF_TOKEN_SCOPE)diff --git a/studio/backend/tests/test_credential_secrets.py b/studio/backend/tests/test_credential_secrets.pyindex 7b5bb56b026..75dee1abecc 100644--- a/studio/backend/tests/test_credential_secrets.py+++ b/studio/backend/tests/test_credential_secrets.py@@ -72,6 +72,35 @@ def test_upsert_and_delete_are_idempotent():assert credential_secrets.delete_provider_api_key("provider-1") is False+def test_one_read_reports_the_value_and_whether_a_row_is_there(isolated_databases):+ """Absent and unreadable are different answers, and the gate now gets both from ONE read.++ Against the real store rather than a stub: the reader it replaced asked `get_hf_token` and+ then `hf_token_row_exists`, so a refactor that collapsed them could satisfy stubbed callers+ while telling a caller that an undecryptable credential is no credential, which authorizes.+ """+ assert credential_secrets.get_hf_token_with_presence() == (None, False)++ credential_secrets.save_hf_token("hf_saved")+ assert credential_secrets.get_hf_token_with_presence() == ("hf_saved", True)++ conn = sqlite3.connect(isolated_databases)+ try:+ row = conn.execute("SELECT ciphertext FROM credential_secrets").fetchone()+ damaged = bytearray(row[0])+ damaged[-1] ^= 1+ conn.execute("UPDATE credential_secrets SET ciphertext = ?", (bytes(damaged),))+ conn.commit()+ finally:+ conn.close()+ assert credential_secrets.get_hf_token_with_presence() == (+ None,+ True,+ ), "an undecryptable row is still a credential this host holds"+ assert credential_secrets.get_hf_token() is None+ assert credential_secrets.hf_token_row_exists() is True++def test_tampering_and_key_loss_fail_closed(isolated_databases):credential_secrets.save_hf_token("hf_private")conn = sqlite3.connect(isolated_databases)diff --git a/studio/backend/tests/test_offline_local_cache_discovery.py b/studio/backend/tests/test_offline_local_cache_discovery.pyindex 7977f1317cf..c9f21b54151 100644--- a/studio/backend/tests/test_offline_local_cache_discovery.py+++ b/studio/backend/tests/test_offline_local_cache_discovery.py@@ -844,7 +844,7 @@ def test_the_ownership_check_reads_the_hosts_token_every_time(monkeypatch, on_di@pytest.mark.parametrize(- ("reader", "target", "raw", "stripped", "failure"),+ ("reader", "target", "raw", "stripped", "failure", "answer"),[("ambient",@@ -852,19 +852,22 @@ def test_the_ownership_check_reads_the_hosts_token_every_time(monkeypatch, on_di" hf_from_hub ","hf_from_hub",OSError("token file unreadable"),+ lambda value: value,),("saved",- "storage.credential_secrets.get_hf_token",+ # Value and presence come back together, so the stub answers as that reader does.+ "storage.credential_secrets.get_hf_token_with_presence"," hf_from_store ","hf_from_store",RuntimeError("credential database is locked"),+ lambda value: (value, value is not None),),],ids = ("the-hosts-own-token", "the-studio-credential-store"),)def test_a_credential_reader_separates_an_absent_credential_from_an_unreadable_one(- monkeypatch, reader, target, raw, stripped, failure+ monkeypatch, reader, target, raw, stripped, failure, answer):read = _REAL_AMBIENT_HF_TOKEN if reader == "ambient" else _REAL_SAVED_STUDIO_HF_TOKENif reader == "ambient":@@ -872,10 +875,10 @@ def test_a_credential_reader_separates_an_absent_credential_from_an_unreadable_ofor key in hf_tokens._HF_TOKEN_ENV_KEYS:monkeypatch.delenv(key, raising = False)- monkeypatch.setattr(target, lambda: raw)+ monkeypatch.setattr(target, lambda: answer(raw))assert read() == (True, stripped)- monkeypatch.setattr(target, lambda: None)+ monkeypatch.setattr(target, lambda: answer(None))assert read() == (True, None)# Asked and NOT answered is the third outcome; collapsing it into "no credential" fails open.@@ -914,24 +917,47 @@ def test_a_credential_held_only_under_a_legacy_alias_still_counts(monkeypatch, aassert _REAL_AMBIENT_HF_TOKEN() == (True, HOST_CREDENTIAL)+def test_a_store_that_answered_absence_once_is_not_asked_again(monkeypatch):+ """One read decides, so a failure that only a SECOND read would have met cannot refuse.++ The reader this replaced asked the store again whenever the first answer was empty, and a+ transient failure on that second ask turned a host with nothing saved into "cannot say",+ which refuses the offline fallback this gate exists to allow. It also closed a window: two+ reads could straddle a save and report absence and presence for one call.+ """+ from storage import credential_secrets++ opened = []+ real_connection = credential_secrets.get_connection++ def flaky(*args, **kwargs):+ opened.append(1)+ if len(opened) >= 2:+ raise RuntimeError("database is locked")+ return real_connection(*args, **kwargs)++ monkeypatch.setattr(credential_secrets, "get_connection", flaky)+ assert _REAL_SAVED_STUDIO_HF_TOKEN() == (True, None)+ assert len(opened) == 1, "a second read is a second answer, and a chance to disagree"++def test_an_unreadable_saved_credential_is_unknown_rather_than_absent(monkeypatch):"""`get_secret` answers None for an absent row AND an undecryptable one; the row EXISTINGseparates them, readable without decrypting anything."""from storage import credential_secretsread = _REAL_SAVED_STUDIO_HF_TOKEN- monkeypatch.setattr(credential_secrets, "get_hf_token", lambda: None)- monkeypatch.setattr(credential_secrets, "hf_token_row_exists", lambda: True)+ monkeypatch.setattr(credential_secrets, "get_hf_token_with_presence", lambda: (None, True))assert read() == (False, None), "an unreadable saved credential must not read as absent"- monkeypatch.setattr(credential_secrets, "hf_token_row_exists", lambda: False)+ monkeypatch.setattr(credential_secrets, "get_hf_token_with_presence", lambda: (None, False))assert read() == (True, None), "a host with nothing saved is still a real answer"def _raises():raise RuntimeError("credential database is locked")- monkeypatch.setattr(credential_secrets, "hf_token_row_exists", _raises)+ monkeypatch.setattr(credential_secrets, "get_hf_token_with_presence", _raises)assert read() == (False, None)