API key is optional beyond this computer: warn, never refuse
The server and strata serve start on 0.0.0.0 without a key and print one plain warning. strata launch gets --no-api-key; the Access screen makes a key by default and t turns it off. api_key "none" in a config means no key on purpose. Cloudflare without a key gets a stronger warning. Docs updated.
This commit is contained in:
1 parent
c0c3a06ce4
commit
e52668857c
21 files changed
+205
-59
No files matched your search
@@ -45,7 +45,7 @@ Follow **[docs/AI_SETUP.md](docs/AI_SETUP.md)**. For an agent that has a shell,
|
||||
4. Connect the user's apps: `strata connect` lists them, `strata connect <app> --check` sends one prompt and one tool
|
||||
call the way that app does.
|
||||
|
||||
Never expose the server beyond `127.0.0.1` without an API key. `--access lan` makes a key for you. The old route (clone
|
||||
Keep the server on `127.0.0.1` unless the user asks for more. Beyond it an API key is recommended: `--access lan` makes one for you, and `--no-api-key` serves without one (a warning, never a refusal; on a public tunnel the warning is stronger). The old route (clone
|
||||
the repository and run `START-HERE.bat --yes` or `./setup.sh --yes`) still works and is the fallback when the
|
||||
Terminal cannot run. Strata's MCP server ([docs/MCP_SERVER.md](docs/MCP_SERVER.md)) offers the same steps as tools.
|
||||
|
||||
|
||||
@@ -246,7 +246,7 @@ strata doctor # check the installed engine file
|
||||
|
||||
`strata --help` lists everything. Starting and serving never download anything. Only the install, `strata launch` (when
|
||||
you choose a model) and `strata update` do. To reach Strata from your phone or another PC, use
|
||||
`strata launch --access lan`. It makes an API key and will not start on a network without one. No browser opens unless
|
||||
`strata launch --access lan`. It makes an API key (recommended; add `--no-api-key` to go without, with a warning). No browser opens unless
|
||||
you add `--open`. Guide: [docs/TERMINAL_LAUNCH.md](docs/TERMINAL_LAUNCH.md). Whole client: [docs/TERMINAL.md](docs/TERMINAL.md).
|
||||
|
||||
### With AI agents
|
||||
|
||||
+6
-4
@@ -13,10 +13,11 @@ Work through the steps in order. Tell the user what you are doing in plain words
|
||||
|
||||
## 0. Ground rules
|
||||
|
||||
- **Never expose the server without an API key.** Keep the default (`--access local`, the server listens on
|
||||
`127.0.0.1` only). Only if the user asks for access from other devices, use `--access lan`. Strata makes a long
|
||||
random key for you then and will not start on a network without one. Give the user the key
|
||||
(`strata launch --show-key`). Never put a tunnel or port forward in front of a server without a key.
|
||||
- **Recommend an API key beyond this computer; do not force it.** Keep the default (`--access local`, the server listens on
|
||||
`127.0.0.1` only, no key needed). Only if the user asks for access from other devices, use `--access lan`. Strata makes a long
|
||||
random key for you then. Give the user the key (`strata launch --show-key`). If the user says they do not want a key, use
|
||||
`--no-api-key`: it starts and warns that anyone who can reach the port can use the model and its tools. Tell the user so.
|
||||
Do not put a tunnel or port forward in front of a server without a key unless the user asks for it.
|
||||
- Do not change the user's system beyond what Strata does. The Terminal installs into the user's home folder and needs
|
||||
no administrator rights. It does not install drivers, Python packages or compilers. Ask before installing drivers.
|
||||
- The model download is ~70 GB (94 GB for Unsloth's UD-IQ4_XS, 111 GB for UD-Q4_K_XL). Confirm the user is fine with
|
||||
@@ -114,6 +115,7 @@ The flags (all of them, with examples: `strata launch --help`):
|
||||
| `--access local\|lan\|cloudflare\|tailscale` | who can connect; beyond `local` a key is made for you |
|
||||
| `--port N` | the server port (default 8080) |
|
||||
| `--api-key KEY`, `--api-key-env NAME`, `--new-key` | the key clients must send |
|
||||
| `--no-api-key` | share without a key (a warning, not a refusal; recommended only on a network you trust) |
|
||||
| `--save-preset NAME` | keep these choices; `strata launch --preset NAME` starts them again |
|
||||
| `--plan` | show what would happen and exit |
|
||||
| `--yes`, `--no-tui` | no questions, no screens |
|
||||
|
||||
+3
-1
@@ -1072,7 +1072,9 @@ print(r.choices[0].message.content)
|
||||
editable there.
|
||||
- **From other devices on your network.** The server listens on your PC only (`127.0.0.1`) unless you say otherwise:
|
||||
run setup with `START-HERE.bat --setup --host 0.0.0.0 --api-key some-long-secret` (or add `"host": "0.0.0.0"` and
|
||||
`"api_key": "..."` to `strata-<model>.json`). The server window then prints this PC's addresses
|
||||
`"api_key": "..."` to `strata-<model>.json`). The key is recommended, not required: without one the server still starts and
|
||||
warns that anyone who can reach the port can use the model and its tools (to say it is on purpose, use `--no-api-key` on
|
||||
the server or `"api_key": "none"` in the config, which silences the config-empty note). The server window then prints this PC's addresses
|
||||
(`from other devices: http://192.168.x.x:8080/`); open that on the other device, or use `.../v1` as an API base URL.
|
||||
On Windows the firewall blocks it until you allow it: accept its prompt for Python (private networks), or run
|
||||
`New-NetFirewallRule -DisplayName "Strata 8080" -Direction Inbound -Protocol TCP -LocalPort 8080 -Action Allow -Profile Private`
|
||||
|
||||
+1
-1
@@ -49,7 +49,7 @@ Like any download, each connection below shows the other side your IP address an
|
||||
| llama.cpp source code (a fixed commit) | github.com/ggml-org/llama.cpp | During a model install, if it is not on your PC yet. Strata uses only its model-preparation scripts |
|
||||
| Web search and web pages | DuckDuckGo, with Bing as the second source; or Exa, Perplexity or DeepSeek if you save a key for them. Any page the agent is asked to open goes to that page's site | When the agent uses its search or "open web pages" tool. In Manual mode it asks you first, once per chat |
|
||||
| Outside model services | The service you add (OpenAI, Anthropic, OpenRouter, a server on your network and others) | Only for chats with that model, and only after you add its key |
|
||||
| Cloudflare tunnel | Cloudflare, through the `cloudflared` program | Only while you have the tunnel on, and it will not start without an API key |
|
||||
| Cloudflare tunnel | Cloudflare, through the `cloudflared` program | Only while you have the tunnel on, and Strata makes an API key for it unless you pass `--no-api-key` (then it warns that anyone who finds the address can use your model) |
|
||||
| Tailscale, local network | Not Strata's traffic. Strata only reads Tailscale's status and shows the address | Only if you choose that access in `strata launch` |
|
||||
| An image link in an API request | The address in the link | Only when a program sends your server a request with an `http(s)` image link. `--offline` refuses it |
|
||||
| Remote tool servers (MCP) | The address you put in the run config | Only when you add one |
|
||||
|
||||
@@ -38,7 +38,7 @@ The release folder is the latest GitHub release of Niko1221/Strata (`https://git
|
||||
8. **Advanced** (optional): every engine setting with default, tuned value and your value; edit, reset, add a setting by name (checked against the engine's own list; a warning, not a refusal);
|
||||
the exact command (it includes the context, memory format and picture choice you made above; it has its own scroll area: Tab, then the arrows) and the matching `strata launch` flags.
|
||||
9. **Access**: this computer only (127.0.0.1), your network (LAN address, key), Cloudflare quick tunnel (needs `cloudflared`), Tailscale (needs it installed and connected); port; API key
|
||||
(made for you beyond this computer: the server will not start on a network without one).
|
||||
(optional, recommended beyond this computer: Strata makes one for you, and one keypress (`t`) turns it off. Without a key the server still starts and warns that anyone who can reach the port can use the model and its tools; `--no-api-key` does the same without the screens, and on a Cloudflare tunnel the warning is stronger. This computer only never needs a key).
|
||||
10. **Save as preset** and launch. Then downloads (with progress), engine start, and the monitor. In a small window the summary shrinks so the three choices stay on screen,
|
||||
and the key line says what Enter will do. No web page opens by itself; only `--open` opens one.
|
||||
|
||||
|
||||
+28
-7
@@ -7200,6 +7200,22 @@ def key_list(value) -> list[str]:
|
||||
return [k.strip() for k in str(value).split(",") if k.strip()]
|
||||
|
||||
|
||||
def explicit_no_key(value) -> bool:
|
||||
"""The owner chose to serve without a key: "api_key": "none" in the config, STRATA_API_KEY=none or --api-key none
|
||||
(or --no-api-key, handled by the caller). Never a key called "none"."""
|
||||
return isinstance(value, str) and value.strip().lower() == "none"
|
||||
|
||||
|
||||
def open_server_warning(port, public=False, tools=False) -> str:
|
||||
"""The one plain warning for a server on the network with no API key (recommend, never force)."""
|
||||
msg = f"no API key: anyone who can reach port {port} can use the model" + (" and its tools" if tools else "") + "."
|
||||
if tools:
|
||||
msg += " The tools can read and change files on this computer."
|
||||
if public:
|
||||
msg += " This address is on the public internet, so anyone who finds it can use it."
|
||||
return msg + " Add an API key to keep others out."
|
||||
|
||||
|
||||
def api_key_of(value):
|
||||
"""The key as a client can send it (#725). An HTTP header loses the spaces and line ends around its value, so a
|
||||
key kept with them (a config file or an environment file with CRLF line ends, a quoted " key ") matched no
|
||||
@@ -7698,6 +7714,9 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in
|
||||
ap.add_argument("--api-key", default=os.environ.get("STRATA_API_KEY", ""),
|
||||
help="require this key on /v1/* (Authorization: Bearer ... or x-api-key); also $STRATA_API_KEY. "
|
||||
"Several keys: separate them with commas (key1,key2), as llama.cpp does")
|
||||
ap.add_argument("--no-api-key", action="store_true",
|
||||
help="serve on the network without an API key (anyone who can reach the port can use the model; "
|
||||
"also \"api_key\": \"none\" in the config). Warns once, never refuses")
|
||||
ap.add_argument("--mcp-config", help="a JSON file with MCP servers in Claude Desktop's format ({\"mcpServers\": "
|
||||
"{...}}); the web app's chat can use their tools (also \"mcp_servers\" in "
|
||||
"the config)")
|
||||
@@ -7803,14 +7822,16 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in
|
||||
x.strip() == "--api-key=" for i, x in enumerate(supplied_args)):
|
||||
print("[strata] an API key was given but it is empty: set a key, or leave it out", file=sys.stderr)
|
||||
return 2
|
||||
raw_key = a.api_key or cfg.get("api_key", "")
|
||||
no_key_chosen = bool(getattr(a, "no_api_key", False)) or explicit_no_key(raw_key)
|
||||
if explicit_no_key(raw_key):
|
||||
raw_key = ""
|
||||
try:
|
||||
preflight_api_key = api_key_of(a.api_key or cfg.get("api_key", ""))
|
||||
preflight_api_key = api_key_of(raw_key)
|
||||
except ValueError as e:
|
||||
print(f"[strata] {e}: set a key, or leave it out", file=sys.stderr)
|
||||
return 2
|
||||
if a.host not in ("127.0.0.1", "localhost", "::1") and not preflight_api_key:
|
||||
print("[strata] a non-loopback bind requires an inference API key", file=sys.stderr, flush=True)
|
||||
return 2
|
||||
# A key is recommended on a network, never required (owner decision 2026-10-20): the banner below warns once.
|
||||
try: # before the minutes of loading: is the port free?
|
||||
Server((a.host, a.port), BaseHTTPRequestHandler).server_close()
|
||||
except OSError as e:
|
||||
@@ -7992,7 +8013,7 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in
|
||||
if set(key_list(svc.api_key)) & set(key_list(svc.telemetry_key)):
|
||||
print("[strata] telemetry_read_key must differ from every inference API key", file=sys.stderr)
|
||||
return 2
|
||||
if not svc.api_key and "api_key" in cfg: # #569: written, but empty: the server has none (a warning, not a stop)
|
||||
if not svc.api_key and "api_key" in cfg and not no_key_chosen: # #569: written, but empty: the server has none (a warning, not a stop)
|
||||
print("[strata] the api_key in the config is empty: this server has no API key (anyone who can reach it can "
|
||||
"use it); set one, or leave api_key out", file=sys.stderr, flush=True)
|
||||
svc.cors_origins = origins_of(cfg.get("cors_origins"), "cors_origins", wildcard=True)
|
||||
@@ -8116,8 +8137,8 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in
|
||||
if not ips:
|
||||
print(" from other devices: http://<this PC's IP address>:" + str(bound_port) + "/", flush=True)
|
||||
if not svc.api_key:
|
||||
print(" WARNING: no API key - anyone on your network can use this model. Add \"api_key\": \"...\" "
|
||||
"to the config (clients send it as their API key; the web page asks for it)", flush=True)
|
||||
print(" WARNING: " + open_server_warning(bound_port, tools=svc.mcp is not None),
|
||||
flush=True)
|
||||
if os.name == "nt":
|
||||
print(" nothing arrives? Windows Firewall blocks it until allowed: accept its prompt for Python, or run "
|
||||
"in an admin PowerShell:\n New-NetFirewallRule -DisplayName \"Strata " + str(bound_port) + "\" "
|
||||
|
||||
@@ -344,5 +344,24 @@ class OverHttp(unittest.TestCase):
|
||||
host="rebind.example.com")[0], 403)
|
||||
|
||||
|
||||
class NoApiKey(unittest.TestCase):
|
||||
"""A key is recommended on a network, never required (owner decision 2026-10-20)."""
|
||||
|
||||
def test_none_means_no_key_on_purpose(self):
|
||||
from serve.server import explicit_no_key
|
||||
for v in ("none", " None ", "NONE"):
|
||||
self.assertTrue(explicit_no_key(v))
|
||||
for v in ("", None, "sk-none", ["none"], "none,x"):
|
||||
self.assertFalse(explicit_no_key(v))
|
||||
|
||||
def test_the_warning_is_plain(self):
|
||||
from serve.server import open_server_warning
|
||||
w = open_server_warning(8080)
|
||||
self.assertIn("anyone who can reach port 8080 can use the model", w)
|
||||
self.assertNotIn("tools", w)
|
||||
self.assertIn("and its tools", open_server_warning(8080, tools=True))
|
||||
self.assertIn("public internet", open_server_warning(8080, public=True))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -7383,7 +7383,7 @@ def main() -> int:
|
||||
ap.add_argument("--no-remote-expert-opt", action="store_true",
|
||||
help="with two or more GPUs: leave out --remote-expert-opt, which setup adds there (#578)")
|
||||
ap.add_argument("--host", help="where the server listens: 127.0.0.1 = this PC only (default), 0.0.0.0 = also other "
|
||||
"devices on your network (issue #26; set --api-key too)")
|
||||
"devices on your network (issue #26; an --api-key is recommended)")
|
||||
ap.add_argument("--api-key", help="require this key from clients (recommended with --host 0.0.0.0); several keys: key1,key2")
|
||||
ap.add_argument("--no-browser", dest="browser", action="store_false", default=None,
|
||||
help="do not open the chat page in the browser when the model is ready (for a harness or an app "
|
||||
|
||||
+9
-8
@@ -684,13 +684,14 @@ def _launch_plan(ref: str, cli: argparse.Namespace | None = None) -> tuple[dict,
|
||||
path, saved, revision, cfg = _source(ref)
|
||||
values, origins = _effective(cfg, saved, cli)
|
||||
host = values["host"]
|
||||
from serve.server import api_key_of, key_list
|
||||
try:
|
||||
has_key = bool(key_list(api_key_of(os.environ.get("STRATA_API_KEY") or cfg.get("api_key", ""))))
|
||||
except ValueError:
|
||||
raise ProfileError("the inference API key is invalid", 5) from None
|
||||
if host not in ("127.0.0.1", "localhost", "::1") and not has_key:
|
||||
raise ProfileError("non-loopback serving requires an API key in the run config or STRATA_API_KEY")
|
||||
from serve.server import api_key_of, explicit_no_key, key_list
|
||||
raw_key = os.environ.get("STRATA_API_KEY") or cfg.get("api_key", "")
|
||||
if not explicit_no_key(raw_key):
|
||||
try:
|
||||
key_list(api_key_of(raw_key))
|
||||
except ValueError:
|
||||
raise ProfileError("the inference API key is invalid", 5) from None
|
||||
# A key is recommended on a network, never required: the server warns once at start (owner decision 2026-10-20).
|
||||
server_args = ["--engine", getattr(cli, "engine", "strata"), "--config", str(path), "--host", str(host),
|
||||
"--port", str(values["port"])]
|
||||
if cli is not None:
|
||||
@@ -1161,7 +1162,7 @@ def _bench_standard(a: argparse.Namespace, machine: bool) -> int:
|
||||
host = "127.0.0.1" if host in ("0.0.0.0", "::") else host
|
||||
authority = f"[{host}]" if ":" in host and not host.startswith("[") else host
|
||||
url = f"http://{authority}:{plan['effective']['port']}"
|
||||
if not key and cfg.get("api_key"):
|
||||
if not key and cfg.get("api_key") and str(cfg["api_key"]).strip().lower() != "none":
|
||||
from serve.server import api_key_of, key_list
|
||||
keys = key_list(api_key_of(cfg["api_key"]))
|
||||
key = keys[0] if keys else None
|
||||
|
||||
@@ -376,7 +376,7 @@ def start_tunnel(name: str, port: int, *, wait: float = 45.0) -> tuple[str | Non
|
||||
stop_tunnel(name)
|
||||
return None, ("The Cloudflare tunnel did not come up in time. Check your internet connection and try again; "
|
||||
"the server itself is running and still works on this computer.")
|
||||
return url, "The Cloudflare tunnel is up. Anyone with the address can reach the server, so keep the API key on." + (" " + note if note else "")
|
||||
return url, "The Cloudflare tunnel is up. Anyone with the address can reach the server; an API key keeps others out." + (" " + note if note else "")
|
||||
|
||||
|
||||
def tunnel_info(name: str) -> dict | None:
|
||||
|
||||
@@ -107,6 +107,7 @@ def add_parsers(sp: argparse._SubParsersAction) -> list[argparse.ArgumentParser]
|
||||
a.add_argument("--api-key", metavar="KEY", help="the key clients must send (made for you when you share beyond this computer)")
|
||||
a.add_argument("--api-key-env", metavar="NAME", help="read the key from this environment variable")
|
||||
a.add_argument("--new-key", action="store_true", help="make a new API key")
|
||||
a.add_argument("--no-api-key", action="store_true", help="share beyond this computer without an API key (a warning is shown, nothing is refused)")
|
||||
o = p.add_argument_group("running")
|
||||
o.add_argument("--save-preset", metavar="NAME", help="save these choices under this name")
|
||||
o.add_argument("--no-tui", action="store_true", help="no screens: serve, print the address and return")
|
||||
@@ -219,6 +220,13 @@ def settings_from_args(a: argparse.Namespace, catalog=None) -> tuple[S.LaunchSet
|
||||
if not val:
|
||||
raise ValueError(f"The environment variable {a.api_key_env} is empty or not set.")
|
||||
s.api_key = val
|
||||
if a.no_api_key:
|
||||
if a.api_key or a.api_key_env:
|
||||
notices.append(S.Notice("warn", "An API key was given as well as --no-api-key, so the key is kept.", ""))
|
||||
else:
|
||||
s.api_key, s.no_key = None, True # also drops a key a saved preset had
|
||||
elif s.api_key:
|
||||
s.no_key = False
|
||||
if a.set:
|
||||
s.extra = {**s.extra, **S.settings_from_pairs(a.set)}
|
||||
if a.save_preset:
|
||||
@@ -258,7 +266,7 @@ def apply_defaults(s: S.LaunchSettings, catalog) -> tuple[S.LaunchSettings, list
|
||||
notices.append(S.Notice("warn", "The engine installed here has no picture reader, so pictures are off.",
|
||||
"Update the engine to read pictures, or add --vision off to silence this."))
|
||||
notices += S.check_context(s, max_fit_tokens=None)
|
||||
if s.access != "local" and not s.api_key:
|
||||
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.",
|
||||
@@ -462,7 +470,7 @@ def launch_info(name: str | None = None) -> dict | None:
|
||||
if pick is None and preset is None:
|
||||
return None
|
||||
port = (pick or {}).get("port") or (preset.port if preset else S.DEFAULT_PORT)
|
||||
return {"url": (pick or {}).get("url") or f"http://127.0.0.1:{port}", "key": cfg.get("api_key") or (preset.api_key if preset else None),
|
||||
return {"url": (pick or {}).get("url") or f"http://127.0.0.1:{port}", "key": (cfg.get("api_key") if str(cfg.get("api_key") or "").strip().lower() != "none" else None) or (preset.api_key if preset else None),
|
||||
"model": cfg.get("model_name") or "strata", "context": _cfg_context(cfg), "running": bool(pick), "name": (pick or {}).get("name") or (preset.name if preset else None),
|
||||
"port": port, "access": preset.access if preset else None}
|
||||
|
||||
@@ -541,7 +549,7 @@ def run_launch(a: argparse.Namespace) -> int:
|
||||
return fail(errors[0].line(), 2)
|
||||
if a.new_key:
|
||||
from strata_cli.launch import access
|
||||
s.api_key = access.new_key()
|
||||
s.api_key, s.no_key = access.new_key(), False
|
||||
if not s.name:
|
||||
s.name = f"{s.model or 'model'} {S.context_label(s.context)}"
|
||||
move_data = _move_data_choice(a, s, catalog, machine)
|
||||
|
||||
@@ -221,6 +221,8 @@ def derive_config(base: dict, s: S.LaunchSettings, *, bool_flags: frozenset[str]
|
||||
cfg["port"] = int(s.port)
|
||||
if s.api_key:
|
||||
cfg["api_key"] = s.api_key
|
||||
elif s.no_key and s.access != "local":
|
||||
cfg["api_key"] = "none" # served without a key on purpose (the server warns once at start)
|
||||
else:
|
||||
cfg.pop("api_key", None)
|
||||
cfg.setdefault("exe", "component:strata-engine")
|
||||
|
||||
@@ -1167,8 +1167,8 @@ class AdvancedScreen(Base):
|
||||
class AccessScreen(Base):
|
||||
step_id = "access"
|
||||
hints = "↑↓ choose Enter next p port k new key t key on/off Esc back ? help"
|
||||
help_text = ("Who can use the model. 'This computer only' is the safe default. Anything beyond it needs the API key: the server will not "
|
||||
"start on a network without one.")
|
||||
help_text = ("Who can use the model. 'This computer only' is the safe default and never needs a key. Beyond it Strata makes an API key "
|
||||
"for you (recommended); press t if you would rather have no key: it still starts, but anyone who can reach it can use it.")
|
||||
|
||||
BINDINGS = Base.BINDINGS + [Binding("p", "port", show=False), Binding("k", "newkey", show=False), Binding("t", "keytoggle", show=False)]
|
||||
|
||||
@@ -1203,7 +1203,7 @@ class AccessScreen(Base):
|
||||
t = Text()
|
||||
t.append(f"\n Port [ {s.port} ] press p to change\n")
|
||||
t.append(f" API key [ {'on' if on else 'off'} ] {acc.mask_key(s.api_key)} ", style=FG if on else WARN)
|
||||
t.append("(recommended for anything beyond this computer)" if beyond else "(optional on this computer)", style=MUTE)
|
||||
t.append(("(recommended for anything beyond this computer; t = no key)" if on else "(t = make a key)") if beyond else "(not needed on this computer)", style=MUTE)
|
||||
self.query_one("#portkey", Static).update(t)
|
||||
|
||||
def explain(self) -> Text:
|
||||
@@ -1217,9 +1217,9 @@ class AccessScreen(Base):
|
||||
if fw:
|
||||
out.append(fw + "\n", style=WARN)
|
||||
if cur.key == "cloudflare":
|
||||
out.append("A Cloudflare quick tunnel gives a temporary public address; anyone with it can try to use the server, so keep the API key on.", style=MUTE)
|
||||
out.append("A Cloudflare quick tunnel gives a temporary public address; anyone with it can try to use the server, so an API key keeps others out.", style=MUTE)
|
||||
elif cur.key == "lan":
|
||||
out.append("Other computers on your network can use it at the address shown. Keep the API key on.", style=MUTE)
|
||||
out.append("Other computers on your network can use it at the address shown. An API key is recommended.", style=MUTE)
|
||||
elif cur.key == "tailscale":
|
||||
out.append("Only devices signed in to your Tailscale network can reach it.", style=MUTE)
|
||||
else:
|
||||
@@ -1230,9 +1230,11 @@ class AccessScreen(Base):
|
||||
kind = self.menu().current.key
|
||||
s = self.ctx.settings
|
||||
s.access = kind
|
||||
if kind != "local" and not s.api_key:
|
||||
if kind != "local" and not s.api_key and not s.no_key:
|
||||
s.api_key = acc.new_key()
|
||||
self.say("An API key was made for you, because this reaches beyond your computer.")
|
||||
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)
|
||||
|
||||
def action_port(self) -> None:
|
||||
self.open_field("portfield", str(self.ctx.settings.port), "port number")
|
||||
@@ -1253,6 +1255,7 @@ class AccessScreen(Base):
|
||||
|
||||
def action_newkey(self) -> None:
|
||||
self.ctx.settings.api_key = acc.new_key()
|
||||
self.ctx.settings.no_key = False
|
||||
self.say("A new API key was made. Apps that used the old one need the new one (strata connect shows it).")
|
||||
self.paint()
|
||||
|
||||
@@ -1260,9 +1263,10 @@ class AccessScreen(Base):
|
||||
s = self.ctx.settings
|
||||
if s.api_key:
|
||||
s.api_key = None
|
||||
self.say("The API key is off." + (" The server will not start on a network without one." if s.access != "local" else ""), s.access != "local")
|
||||
s.no_key = s.access != "local"
|
||||
self.say("The API key is off." + ((" " + (S.NO_KEY_PUBLIC if s.access == "cloudflare" else S.NO_KEY_NETWORK)) if s.access != "local" else ""), s.access != "local")
|
||||
else:
|
||||
s.api_key = acc.new_key()
|
||||
s.api_key, s.no_key = acc.new_key(), False
|
||||
self.say("The API key is on.")
|
||||
self.paint()
|
||||
|
||||
@@ -1275,7 +1279,7 @@ class AccessScreen(Base):
|
||||
def commit(self) -> None:
|
||||
s = self.ctx.settings
|
||||
s.access = self.menu().current.key
|
||||
if s.access != "local" and not s.api_key:
|
||||
if s.access != "local" and not s.api_key and not s.no_key:
|
||||
s.api_key = acc.new_key()
|
||||
|
||||
def action_back(self) -> None:
|
||||
|
||||
@@ -92,6 +92,7 @@ class LaunchSettings:
|
||||
access: str = "local"
|
||||
port: int = DEFAULT_PORT
|
||||
api_key: str | None = None # never shown whole; stored only in the private preset file
|
||||
no_key: bool = False # served beyond this computer without a key, on purpose (--no-api-key); a warning, never a refusal
|
||||
extra: dict[str, str] = field(default_factory=dict) # Advanced: --set key=value (flags and STRATA_* variables)
|
||||
# filled in by the run, kept in the preset
|
||||
tuned_preset: str | None = None # id of the tuning preset the tuner saved
|
||||
@@ -153,6 +154,11 @@ def check_port(port: Any) -> Notice | None:
|
||||
return None
|
||||
|
||||
|
||||
NO_KEY_NETWORK = "No API key: anyone who can reach this port can use the model and its tools (they can read and change files on this computer)."
|
||||
NO_KEY_PUBLIC = ("No API key on a public address: anyone on the internet who finds it can use the model and its tools "
|
||||
"(they can read and change files on this computer).")
|
||||
|
||||
|
||||
def check_access(s: LaunchSettings) -> list[Notice]:
|
||||
out: list[Notice] = []
|
||||
if s.access not in ACCESS_KINDS:
|
||||
@@ -164,8 +170,13 @@ def check_access(s: LaunchSettings) -> list[Notice]:
|
||||
if port:
|
||||
out.append(port)
|
||||
if s.access != "local" and not s.api_key:
|
||||
out.append(Notice("warn", f"{ACCESS_WORDS[s.access]} without an API key lets anyone who can reach it use your computer's model.",
|
||||
"Add an API key (Strata makes one for you in the Access step)."))
|
||||
if s.access == "cloudflare":
|
||||
out.append(Notice("warn", NO_KEY_PUBLIC, "Leave --no-api-key out to get a key."))
|
||||
elif s.no_key:
|
||||
out.append(Notice("warn", NO_KEY_NETWORK, "Leave --no-api-key out to get a key."))
|
||||
else:
|
||||
out.append(Notice("warn", f"{ACCESS_WORDS[s.access]} without an API key lets anyone who can reach it use your computer's model.",
|
||||
"Add an API key (Strata makes one for you in the Access step)."))
|
||||
return out
|
||||
|
||||
|
||||
|
||||
@@ -46,6 +46,8 @@ def _credential(source_bytes: bytes) -> str | None:
|
||||
if not isinstance(cfg, dict):
|
||||
raise ValueError("run config must be an object")
|
||||
raw = os.environ.get("STRATA_API_KEY") or cfg.get("api_key", "")
|
||||
if str(raw).strip().lower() == "none": # "api_key": "none" = served without a key on purpose
|
||||
return None
|
||||
keys = key_list(api_key_of(raw))
|
||||
return keys[0] if keys else None
|
||||
|
||||
|
||||
@@ -43,6 +43,17 @@ class SettingsRules(unittest.TestCase):
|
||||
self.assertEqual(S.check_parallel(S.LaunchSettings(parallel=9), vram_gb=12)[0].level, "error")
|
||||
self.assertEqual(S.check_parallel(S.LaunchSettings(parallel=2), vram_gb=24), [])
|
||||
|
||||
def test_no_key_warnings_are_plain_and_stronger_in_public(self):
|
||||
lan = S.check_access(S.LaunchSettings(access="lan", no_key=True))
|
||||
self.assertEqual([n.level for n in lan], ["warn"])
|
||||
self.assertIn("anyone who can reach this port can use the model and its tools", lan[0].line())
|
||||
pub = S.check_access(S.LaunchSettings(access="cloudflare", no_key=True))
|
||||
self.assertEqual([n.level for n in pub], ["warn"])
|
||||
self.assertIn("public address", pub[0].line())
|
||||
self.assertIn("anyone on the internet", pub[0].line())
|
||||
self.assertEqual(S.check_access(S.LaunchSettings(access="lan", api_key="k")), [])
|
||||
self.assertEqual(S.check_access(S.LaunchSettings(access="local", no_key=True)), [])
|
||||
|
||||
def test_access_notes(self):
|
||||
self.assertEqual(S.check_access(S.LaunchSettings(access="local")), [])
|
||||
lan = S.check_access(S.LaunchSettings(access="lan"))
|
||||
@@ -294,6 +305,14 @@ class RunConfig(unittest.TestCase):
|
||||
self.assertEqual(cfg["host"], "127.0.0.1")
|
||||
self.assertNotIn("api_key", cfg)
|
||||
|
||||
def test_no_key_is_written_as_none_and_a_key_wins(self):
|
||||
cfg = derive_config(self.BASE, S.LaunchSettings(access="lan", no_key=True), bool_flags=frozenset())
|
||||
self.assertEqual((cfg["host"], cfg["api_key"]), ("0.0.0.0", "none"))
|
||||
cfg = derive_config(self.BASE, S.LaunchSettings(access="lan", no_key=True, api_key="sk-x"), bool_flags=frozenset())
|
||||
self.assertEqual(cfg["api_key"], "sk-x")
|
||||
cfg = derive_config(self.BASE, S.LaunchSettings(access="local", no_key=True), bool_flags=frozenset())
|
||||
self.assertNotIn("api_key", cfg)
|
||||
|
||||
def test_installed_config_matching(self):
|
||||
d = {"context": 32768, "kv": "int8", "images": "off"}
|
||||
self.assertTrue(desc_matches(d, S.LaunchSettings(context=32768)))
|
||||
@@ -742,6 +761,23 @@ class FlagsCommand(unittest.TestCase):
|
||||
p = self.plan("--model", "q2_0", "--new-key")
|
||||
self.assertEqual(p["settings"]["api_key"], "set")
|
||||
|
||||
def test_no_api_key_flag(self):
|
||||
p = self.plan("--model", "q2_0", "--access", "lan", "--no-api-key")
|
||||
self.assertIsNone(p["settings"]["api_key"])
|
||||
self.assertFalse(any("new API key was made" in w for w in p["warnings"]))
|
||||
self.assertTrue(any("anyone who can reach this port can use the model and its tools" in w for w in p["warnings"]))
|
||||
p = self.plan("--model", "q2_0", "--access", "cloudflare", "--no-api-key")
|
||||
self.assertTrue(any("public address" in w and "anyone on the internet" in w for w in p["warnings"]))
|
||||
p = self.plan("--model", "q2_0", "--access", "local", "--no-api-key")
|
||||
self.assertEqual([w for w in p["warnings"] if "API key" in w], [])
|
||||
# scripts that name LAN without a key flag keep getting a key, as before
|
||||
p = self.plan("--model", "q2_0", "--access", "lan", "--yes")
|
||||
self.assertEqual(p["settings"]["api_key"], "set")
|
||||
self.assertTrue(any("new API key was made" in w for w in p["warnings"]))
|
||||
# a key given as well wins over --no-api-key, with a note
|
||||
p = self.plan("--model", "q2_0", "--access", "lan", "--api-key", "sk-a", "--no-api-key")
|
||||
self.assertEqual(p["settings"]["api_key"], "set")
|
||||
|
||||
def test_model_path_is_used_instead_of_a_catalog_model(self):
|
||||
p = self.plan("--model-path", "/data/models/IQ3_XXS")
|
||||
s = p["settings"]
|
||||
|
||||
@@ -715,9 +715,30 @@ class AccessStep(Base):
|
||||
self.assertNotEqual(ctx.settings.api_key, first)
|
||||
await press(pilot, "t")
|
||||
self.assertIsNone(ctx.settings.api_key)
|
||||
self.assertIn("will not start on a network without one", text_of(app))
|
||||
self.assertTrue(ctx.settings.no_key)
|
||||
self.assertIn("anyone who can reach this port can use the model and its tools", text_of(app))
|
||||
await press(pilot, "t")
|
||||
self.assertTrue(ctx.settings.api_key)
|
||||
self.assertFalse(ctx.settings.no_key)
|
||||
self.run_app(case)
|
||||
|
||||
def test_default_is_a_key_and_no_key_survives_moving_on(self):
|
||||
async def case(app, pilot, ctx):
|
||||
await press(pilot, *self.reach(), "down")
|
||||
self.assertTrue(ctx.settings.api_key) # default: Strata makes a key
|
||||
await press(pilot, "t") # one keypress: no key
|
||||
await press(pilot, "down") # moving the cursor does not bring the key back
|
||||
await press(pilot, "up")
|
||||
self.assertIsNone(ctx.settings.api_key)
|
||||
self.assertTrue(ctx.settings.no_key)
|
||||
self.run_app(case)
|
||||
|
||||
def test_local_never_asks_for_a_key(self):
|
||||
async def case(app, pilot, ctx):
|
||||
await press(pilot, *self.reach())
|
||||
self.assertEqual(ctx.settings.access, "local")
|
||||
self.assertIsNone(ctx.settings.api_key)
|
||||
self.assertNotIn("An API key was made", text_of(app))
|
||||
self.run_app(case)
|
||||
|
||||
|
||||
|
||||
@@ -845,6 +845,20 @@ class RuntimeTests(unittest.TestCase):
|
||||
self.assertEqual(plan["effective"]["host"], "0.0.0.0")
|
||||
self.assertNotIn("first", json.dumps(plan))
|
||||
|
||||
def test_remote_bind_without_a_key_is_planned_not_refused(self):
|
||||
# owner decision 2026-10-20: a key is recommended on a network, never required
|
||||
from strata_cli.cli import _launch_plan
|
||||
for key in (None, "none"):
|
||||
cfg = json.loads(self.config.read_text())
|
||||
cfg["host"] = "0.0.0.0"
|
||||
cfg.pop("api_key", None)
|
||||
if key:
|
||||
cfg["api_key"] = key
|
||||
self.config.write_text(json.dumps(cfg))
|
||||
with mock.patch.dict(os.environ, {"STRATA_API_KEY": ""}):
|
||||
plan, args = _launch_plan("local")
|
||||
self.assertEqual(plan["effective"]["host"], "0.0.0.0")
|
||||
|
||||
def test_lazy_model_is_verified_as_unloaded_without_generation(self):
|
||||
cfg = json.loads(self.config.read_text())
|
||||
cfg["lazy_load"] = True
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
@@ -588,22 +589,21 @@ class ContractTests(unittest.TestCase):
|
||||
with self.assertRaisesRegex(ValueError, "offline mode cannot download"):
|
||||
svc.prepare(messages, [], {})
|
||||
|
||||
def test_non_loopback_serve_requires_inference_key(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
profile = Path(directory) / "model.json"
|
||||
profile.write_text('{"host":"0.0.0.0","args":[]}', encoding="utf-8")
|
||||
with mock.patch.dict(os.environ, {"STRATA_API_KEY": ""}), redirect_stdout(io.StringIO()):
|
||||
self.assertEqual(main(["serve", "--profile", str(profile)]), 2)
|
||||
|
||||
def test_direct_server_rejects_remote_bind_before_engine_load(self):
|
||||
def test_direct_server_remote_bind_without_key_reaches_engine_load(self):
|
||||
# no early exit over the key any more: every way of saying "no key" gets past the key check
|
||||
import serve.server as server
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
profile = Path(directory) / "model.json"
|
||||
profile.write_text('{"args":[]}', encoding="utf-8")
|
||||
with mock.patch.dict(os.environ, {}, clear=True), \
|
||||
mock.patch.object(server, "StrataEngine", side_effect=AssertionError("engine started")):
|
||||
self.assertEqual(server.main(["--engine", "strata", "--config", str(profile),
|
||||
"--host", "0.0.0.0", "--port", "0"]), 2)
|
||||
cases = [('{"args":[]}', []), ('{"args":[],"api_key":"none"}', []), ('{"args":[]}', ["--no-api-key"]),
|
||||
('{"args":[]}', ["--api-key", "none"])]
|
||||
for body, extra in cases:
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
profile = Path(directory) / "model.json"
|
||||
profile.write_text(body, encoding="utf-8")
|
||||
err = io.StringIO()
|
||||
with mock.patch.dict(os.environ, {}, clear=True), contextlib.redirect_stderr(err):
|
||||
with self.assertRaises(SystemExit):
|
||||
server.main(["--engine", "strata", "--config", str(profile),
|
||||
"--host", "0.0.0.0", "--port", "0", *extra])
|
||||
self.assertIn("tokenizer is missing", err.getvalue(), (body, extra)) # past the key check, stopped later
|
||||
|
||||
def test_code_run_uses_missing_component_exit_until_shared_harness_arrives(self):
|
||||
output = io.StringIO()
|
||||
|
||||
+5
-2
@@ -1241,12 +1241,15 @@ class Strata:
|
||||
|
||||
def api_key_for(self, port: int) -> str | None:
|
||||
"""The key a config of this folder set for that port (used for our own requests; never shown)."""
|
||||
def real(cfg): # "api_key": "none" = served without a key on purpose
|
||||
k = cfg.get("api_key")
|
||||
return k if k and str(k).strip().lower() != "none" else None
|
||||
for c in self.configs():
|
||||
cfg = self.read_config(c)
|
||||
if cfg.get("api_key") and int(cfg.get("port", DEFAULT_PORT)) == port:
|
||||
if real(cfg) and int(cfg.get("port", DEFAULT_PORT)) == port:
|
||||
return cfg["api_key"]
|
||||
for c in self.configs():
|
||||
if self.read_config(c).get("api_key"):
|
||||
if real(self.read_config(c)):
|
||||
return self.read_config(c)["api_key"]
|
||||
return None
|
||||
|
||||
|
||||
Reference in new issue
Block a user