launch keeps the API key it made until --new-key is given (E05/G01)
This commit is contained in:
1 parent
217ddda0eb
commit
f6db09bae2
4 files changed
+97
-5
No files matched your search
@@ -309,6 +309,50 @@ def new_key() -> str:
|
||||
return "sk-strata-" + secrets.token_urlsafe(24)
|
||||
|
||||
|
||||
def _config_key(path) -> str | None:
|
||||
try:
|
||||
key = str(json.loads(Path(path).read_text(encoding="utf-8-sig")).get("api_key") or "").strip()
|
||||
except (OSError, ValueError, AttributeError):
|
||||
return None
|
||||
return key if key and key.lower() != "none" else None
|
||||
|
||||
|
||||
def kept_key(name: str | None = None) -> str | None:
|
||||
"""The API key an earlier launch already made, so a restart does not invalidate the apps set up with it (E05/G01): the key in this launch's
|
||||
own config (profile `launch-<name>`), the saved preset's, else the one in the newest launch config. None when there is none; `--new-key`
|
||||
and the key button are the only ways to rotate it."""
|
||||
try:
|
||||
from strata_control import profiles
|
||||
from strata_cli.launch import settings as S, store
|
||||
if name:
|
||||
try:
|
||||
prof, _rev = profiles.load("launch-" + S.slug(name))
|
||||
key = _config_key(prof.get("source_config"))
|
||||
if key:
|
||||
return key
|
||||
except Exception: # noqa: BLE001 - no such profile yet
|
||||
pass
|
||||
preset = store.load(name, missing_ok=True)
|
||||
if preset and preset.api_key:
|
||||
return preset.api_key
|
||||
newest, found = -1.0, None
|
||||
for row in profiles.list_profiles():
|
||||
if not row["id"].startswith("launch-"):
|
||||
continue
|
||||
key = _config_key(row["source_config"])
|
||||
if not key:
|
||||
continue
|
||||
try:
|
||||
stamp = Path(row["source_config"]).stat().st_mtime
|
||||
except OSError:
|
||||
continue
|
||||
if stamp > newest:
|
||||
newest, found = stamp, key
|
||||
return found
|
||||
except Exception: # noqa: BLE001 - never block a launch over the lookup
|
||||
return None
|
||||
|
||||
|
||||
def mask_key(key: str | None) -> str:
|
||||
if not key:
|
||||
return "off"
|
||||
|
||||
@@ -304,9 +304,14 @@ def apply_defaults(s: S.LaunchSettings, catalog) -> tuple[S.LaunchSettings, list
|
||||
notices += S.check_context(s, max_fit_tokens=None)
|
||||
if s.access != "local" and not s.api_key and not s.no_key:
|
||||
from strata_cli.launch import access
|
||||
s.api_key = access.new_key()
|
||||
notices.append(S.Notice("warn", "A new API key was made, because the server is shared beyond this computer.",
|
||||
"It is saved with the preset; show it with: strata launch --show-key"))
|
||||
kept = access.kept_key(s.name or f"{s.model or 'model'} {S.context_label(s.context)}")
|
||||
s.api_key = kept or access.new_key()
|
||||
if kept:
|
||||
notices.append(S.Notice("warn", "The API key from the earlier launch is kept, so apps that use it keep working.",
|
||||
"A different one: add --new-key. Show it with: strata launch --show-key"))
|
||||
else:
|
||||
notices.append(S.Notice("warn", "A new API key was made, because the server is shared beyond this computer.",
|
||||
"It is saved with the preset; show it with: strata launch --show-key"))
|
||||
notices += gpu_notices(s, comp)
|
||||
notices += S.check_access(s)
|
||||
vram = comp.main_vram_gb or None
|
||||
|
||||
@@ -1340,7 +1340,7 @@ class AccessScreen(Base):
|
||||
s = self.ctx.settings
|
||||
s.access = kind
|
||||
if kind != "local" and not s.api_key and not s.no_key:
|
||||
s.api_key = acc.new_key()
|
||||
s.api_key = acc.kept_key() or acc.new_key()
|
||||
self.say("An API key was made for you (recommended beyond this computer). Press t if you want no key.")
|
||||
elif kind != "local" and s.no_key:
|
||||
self.say(S.NO_KEY_PUBLIC if kind == "cloudflare" else S.NO_KEY_NETWORK, True)
|
||||
@@ -1389,7 +1389,7 @@ class AccessScreen(Base):
|
||||
s = self.ctx.settings
|
||||
s.access = self.menu().current.key
|
||||
if s.access != "local" and not s.api_key and not s.no_key:
|
||||
s.api_key = acc.new_key()
|
||||
s.api_key = acc.kept_key() or acc.new_key()
|
||||
|
||||
def action_back(self) -> None:
|
||||
if self.input_open():
|
||||
|
||||
@@ -41,5 +41,48 @@ class StatusLogsDiscoveryTests(unittest.TestCase):
|
||||
self.assertEqual(endpoint.call_args[0][0], "http://127.0.0.1:9999")
|
||||
|
||||
|
||||
class KeptKeyTests(unittest.TestCase):
|
||||
"""#8 (E05/G01): a key made for a launch survives a restart."""
|
||||
|
||||
def setUp(self):
|
||||
import tempfile
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.cfg = os.path.join(self.temp.name, "launch.json")
|
||||
|
||||
def _write(self, key):
|
||||
with open(self.cfg, "w", encoding="utf-8") as f:
|
||||
json.dump({"api_key": key}, f)
|
||||
|
||||
def test_key_of_the_launch_config_is_kept(self):
|
||||
from strata_cli.launch import access
|
||||
self._write("sk-strata-AAA")
|
||||
with mock.patch("strata_control.profiles.load", return_value=({"source_config": self.cfg}, "r")):
|
||||
self.assertEqual(access.kept_key("gyro-s 32K"), "sk-strata-AAA")
|
||||
|
||||
def test_no_key_and_none_are_not_kept(self):
|
||||
from strata_cli.launch import access
|
||||
self._write("none")
|
||||
with mock.patch("strata_control.profiles.load", return_value=({"source_config": self.cfg}, "r")), mock.patch("strata_control.profiles.list_profiles", return_value=[]):
|
||||
self.assertIsNone(access.kept_key("gyro-s 32K"))
|
||||
|
||||
def test_newest_launch_config_is_the_fallback(self):
|
||||
from strata_cli.launch import access
|
||||
self._write("sk-strata-BBB")
|
||||
rows = [{"id": "launch-other", "source_config": self.cfg}, {"id": "other", "source_config": "x"}]
|
||||
with mock.patch("strata_control.profiles.load", side_effect=Exception("none")), mock.patch("strata_cli.launch.store.load", return_value=None), mock.patch("strata_control.profiles.list_profiles", return_value=rows):
|
||||
self.assertEqual(access.kept_key("gyro-s 64K"), "sk-strata-BBB")
|
||||
|
||||
def test_apply_defaults_reuses_the_key_and_new_key_is_a_different_step(self):
|
||||
from strata_cli.launch import cmd, settings as S
|
||||
from tests.terminal.launch_support import HW_12, Home, catalog
|
||||
s = S.LaunchSettings(family="qwen", model="IQ3_XXS")
|
||||
s.access = "lan"
|
||||
with Home(), mock.patch("strata_cli.launch.access.kept_key", return_value="sk-strata-KEPT"):
|
||||
s2, notes = cmd.apply_defaults(s, catalog(HW_12))
|
||||
self.assertEqual(s2.api_key, "sk-strata-KEPT")
|
||||
self.assertFalse(any("A new API key was made" in n.line() for n in notes))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user