Skip to content

Studio: let LAN access bind only the addresses you choose - #12839

Merged
danielhanchen merged 11 commits into
unslothai:mainfrom
KafKafrnZ:fix/studio-bind-address
Oct 12, 2026
Merged

danielhanchen merged 11 commits into
unslothai:mainfrom
KafKafrnZ:fix/studio-bind-address

Conversation

@KafKafrnZ

@KafKafrnZ KafKafrnZ commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #11822.

LAN access binds every address the machine has, public ones included, and only the port can be changed. On a VPS with a public IP on its network card, there's no way to serve Studio only on a Tailscale or private address: turning LAN access on always exposes the public IP too, then warns about it.

Settings > Remote & LAN > LAN access now has an Addresses setting, next to Port and built the same way:

  • Automatic (the default) keeps today's behavior: every detected address.
  • Choose binds only the addresses you tick. Choose starts with the private addresses ticked and the public ones unticked, so a public address only gets bound when you tick it yourself.

Choose with a public, a private and a Tailscale address detected

This machine only has one private address, so for this screenshot I stubbed the detected addresses in the browser to match a VPS on a tailnet. Everything else is the real UI and backend.

A saved choice after a reload, on a real machine

Root cause

start_lan_listener (studio/backend/lan_access.py) binds every address detect_lan_addresses() returns. The detection keeps public addresses on purpose, since a VPS serving on its own public IP is a valid setup, but nothing let the user leave any of them out.

How it works

  • Setting (utils/lan_access_settings.py): stored as lan_access_addresses, like lan_access_port. None means Automatic; a list means only those addresses. Validation accepts only IPv4 addresses the listener could bind. It rejects loopback, link-local, multicast, unspecified and reserved addresses, leading-zero forms, an empty list and more than 64 addresses.
  • Start: start_lan_access passes the saved choice to start_lan_listener, which binds only the detected addresses that are in it. A chosen address that isn't up right now, like a Tailscale interface that's down, is skipped and logged. If none of the chosen addresses is on the machine, the start fails with selected_address_unavailable and never falls back to binding everything.
  • Fails closed: if the saved choice can't be read or is corrupt, status shows Automatic (as the port setting does), but starting refuses (lan_access_addresses_unavailable / _invalid). Falling back to Automatic would bind the public addresses the user excluded.
  • API: PUT /api/settings/lan-access/addresses with {"addresses": [...] | null}. It's owner-only and needs a UI session, like the other /lan-access routes. Malformed input gets a 422, and a change while LAN access is running gets a 409. GET /lan-access adds configured_addresses and available_addresses (each with a public flag). Detection is skipped for -H launches, since the launch already decides the bind.
  • UI (lan-access-section.tsx): an Automatic/Choose select with a checkbox per address. Public addresses are labeled, and a saved address that isn't up right now is still shown, marked "Not on this machine right now". The section only shows the setting when the backend reports configured_addresses, as it does for the port, so a newer frontend still works with an older backend.

Tests

  • tests/test_lan_access_settings.py: 10 new tests. They cover validation and storage; a corrupt or unreadable choice refusing to start; the choice reaching the listener; save refused while online or on Colab; status listing addresses with public flags; detection failures not breaking status; the HTTP route (422 / 200 / 409); and the bind itself. The bind tests check that a choice binds only the chosen addresses, that a chosen address that isn't up is skipped, that Automatic still binds everything, and that a choice with nothing detected binds nothing. The new tests fail on main and pass with this change (the Automatic test passes on both, as it should).
  • tests/test_account_chat_settings.py: the new route is added to the list of owner-only routes that must reject managed accounts. The guard in test_management_rejects_api_keys now expects 6 UI-session-gated /lan-access handlers instead of 5.
  • frontend/tests/lan-access-state.test.ts: 8 new tests for normalization, an older backend without the field, read-only rules, the private-first default choice, set comparison for the Save button, saved addresses that aren't up, and the error message.

Ran on Windows 11 with Python 3.12:

  • test_lan_access_settings.py + test_account_chat_settings.py: 213 passed.
  • Every other backend test file that imports the changed modules: no new failures. The only failures are the same ones main has on Windows, from symlinks, memlock and missing torch.
  • Frontend: lan-access-state.test.ts 35 passed. The full suite has no new failures; the 2 that fail also fail on main.
  • ruff check passes, ruff format with the pinned 0.6.9 and the kwarg-spacing hook, biome check adds no new errors, and codespell passes.
  • I also tested it end to end against a local Studio: saved a choice from the UI, reloaded, and the choice stayed.

Unrelated: after rebasing on today's main, npm run typecheck fails in tests/settings-deep-open-requests.test.ts, which still references the chat-canvas-network target that #12804 removed. This PR doesn't touch either file.

Follow-up commits

  • 19800a4bd A saved choice that can't be decoded (for example a truncated value_json row) no longer reads as Automatic. get_app_setting returns its fallback both for a missing row and for an undecodable one, so a corrupt row bound every address, including the excluded ones. Only a missing row means Automatic now; an undecodable one refuses to start. Reproduced against a real sqlite store: before the fix, start bound both addresses; after, it refuses with lan_access_addresses_invalid.
  • 312230d3d Start stays disabled while the address choice is unsaved. Start binds the saved choice, so ticking only a Tailscale address and pressing Start without Save bound every address.
  • fa987d762 For the same reason, Start automatically can't be turned on while the choice is unsaved (turning it off is still allowed).
  • 90ab80adc Status now reports configured_public_addresses, so a saved public address that is down keeps its public warning.
  • Merged current main, plus two comment-only trims.

Real-socket check on Linux, using two local IPv4 addresses (one stood in for a public NIC, the other for a tailnet address): on main both are bound and reachable. With Choose and only the tailnet address ticked, only that one is bound and the other refuses connections. A chosen address that isn't up is skipped. If none of the chosen addresses is up, start refuses instead of binding everything.

Before / after

Settings > Remote & LAN > LAN access, as it opens. The Addresses row is new:

LAN access section before and after

After saving a choice of one detected address plus a Tailscale address that isn't up on this machine, then reloading:

Saved choice with an address that is not up

With an unsaved edit, Start and Start automatically stay disabled until Save:

Unsaved edit keeps Start disabled

Studio UI regression check

Base 658b75a68 vs head 633139ff3. Functional: NO_REGRESSION, UI coverage 62%, 1 visual change(s), 3 text-only change(s). Only steps whose screenshots differ are shown.

settings/s07_tab_remote_lan: | reproduced on confirm (VISUAL_DIFF)
settings/s07_tab_remote_lan

Step Text / structure change
settings/s00_open {'removed': ['Auto is using Xet on this machine.', 'no cached verdict; defaulting to Xet'], 'added': []}
settings/s06_tab_api {'removed': [], 'added': ['Addresses', 'Automatic uses every address this machine has, public ones included. Choose uses only the addresses you tick, such as a
crawl/r_projects

@KafKafrnZ

Copy link
Copy Markdown
Contributor Author

Rebased onto main to pick up #12906. The only conflict was one import line in lan-access-section.tsx. The new API-page LAN URLs work with this PR, since settings-managed urls come from the addresses the listener actually bound, so only the chosen ones are shown. Typecheck and the LAN backend/frontend tests pass locally. I'll keep this rebased as main moves.

@danielhanchen

danielhanchen commented Oct 8, 2026 •

Copy link
Copy Markdown
Member

Review record for #12839, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#541.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1: reviewed mirror 899c6aabf (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/backend/utils/lan_access_settings.py (on the mirror)

@@ -232,6 +237,104 @@ def lan_access_port_candidates() -> tuple[int, ...]:
     return tuple(range(DEFAULT_LAN_ACCESS_PORT, LAST_LAN_ACCESS_PORT + 1))
 
 
+def normalize_lan_access_addresses(addresses: Any) -> Optional[tuple[str, ...]]:
+    """``None`` is Automatic; else a de-duplicated tuple of bindable IPv4 literals, detected right now or not."""
+    if addresses is None:
+        return None
+    if not isinstance(addresses, (list, tuple)):
+        raise ValueError("LAN access addresses must be a list of IPv4 addresses.")
+    normalized: list[str] = []
+    for value in addresses:
+        if not isinstance(value, str):
+            raise ValueError("LAN access addresses must be a list of IPv4 addresses.")
+        try:
+            parsed = ipaddress.IPv4Address(value.strip())
+        except ValueError:
+            raise ValueError(f"{value!r} is not an IPv4 address.") from None
+        if (
+            parsed.is_loopback
+            or parsed.is_link_local
+            or parsed.is_multicast
+            or parsed.is_unspecified
+            or parsed.is_reserved
+        ):
+            raise ValueError(f"{value!r} cannot be reached from another device.")
+        if str(parsed) not in normalized:
+            normalized.append(str(parsed))
+    if not normalized:
+        raise ValueError("Choose at least one LAN access address, or Automatic.")
+    if len(normalized) > _MAX_LAN_ACCESS_ADDRESSES:
+        raise ValueError(f"At most {_MAX_LAN_ACCESS_ADDRESSES} LAN access addresses can be chosen.")
+    return tuple(normalized)
+
+
+def _read_lan_access_addresses(*, strict: bool) -> Optional[tuple[str, ...]]:
+    """Strict reads (a start) fail closed: Automatic here would bind the addresses the user excluded."""
+    try:
+        from storage.studio_db import get_app_setting, get_app_settings
+        stored = get_app_setting(LAN_ACCESS_ADDRESSES_KEY, _UNREADABLE)
+        # the fallback also answers an undecodable row; only a missing row is Automatic
+        if stored is _UNREADABLE and LAN_ACCESS_ADDRESSES_KEY not in get_app_settings(
+            [LAN_ACCESS_ADDRESSES_KEY]
+        ):
+            stored = None
+    except Exception as exc:
+        if strict:
+            raise RuntimeError("lan_access_addresses_unavailable") from exc
+        return None
+    if stored is _UNREADABLE:
+        if strict:
+            raise RuntimeError("lan_access_addresses_invalid")

P2 Badge Surface unreadable address selections in the UI

When the saved row is malformed or cannot be read, these exceptions occur before start_lan_listener can record an error. The non-strict status read simultaneously represents the same setting as Automatic, while perform("start", ...) in lan-access-section.tsx discards the failed request's detail, so clicking Start silently returns to Off with Automatic selected and its Save button disabled. Surface lan_access_addresses_invalid and lan_access_addresses_unavailable through status or the failed start response so the owner can diagnose and reset the setting.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Not changing: this needs a corrupt settings row (Studio only writes it via json.dumps), the start already fails closed with nothing bound, the saved port setting behaves the same way, and saving any choice from the picker overwrites the bad row.

Round 2: reviewed mirror 9c2eb4bd17 (this PR's fa987d762)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 9c2eb4bd17

No triage reaction was recorded on the mirror

Rounds 2 and 3 (summarised: their threads were pruned on the mirror before this record was exported)

  • P2 "Preserve public warnings for unavailable saved addresses" on lan-access-state.ts: a saved public address that is not detected right now lost its public warning. Agreed and fixed in 90ab80adc (status reports configured_public_addresses; tests in both suites).
  • P1 "Block auto-start while the address choice is unsaved" on lan-access-section.tsx: turning on Start automatically with an unsaved choice would bind every address at the next launch. Agreed and fixed in fa987d762 (the switch cannot be turned on while the choice is unsaved).

Verdict

The round converged at mirror 9c2eb4bd17 (this PR's fa987d762).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

danielhanchen added a commit to LeoBorcherding/unsloth that referenced this pull request Oct 8, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 8, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 8, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 8, 2026
KafKafrnZ and others added 7 commits October 9, 2026 18:03
LAN access bound every detected address, public ones included, and only the
port was configurable. A VPS on a tailnet had no way to serve on its Tailscale
address without also exposing its public IP.

Settings > Remote & LAN > LAN access gets an Addresses setting, built like the
existing port setting. Automatic keeps today's behavior. Choose binds only the
ticked addresses; a chosen address that is not up is skipped, and a start with
none of them present fails closed instead of falling back to every address.
An unreadable saved choice also refuses to start rather than reading as
Automatic.

Fixes unslothai#11822

Co-Authored-By: Claude Opus 5.5 <[email protected]>
get_app_setting returns its fallback for a missing row and for an undecodable
one alike, so a corrupt lan_access_addresses row read as Automatic and the
listener bound every address, including the ones the user excluded. Only a
missing row means Automatic now; an undecodable one refuses to start.
Start binds the saved choice, so ticking only a Tailscale address and
pressing Start without Save bound every address, public ones included.
Status now reports which saved addresses are public, so a saved public
address that is not detected right now still shows the warning instead of
reading as private.
Boot auto-start binds the saved choice too, so turning it on with an
unsaved choice would bind every address at the next launch.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-12T07:33:21.187661Z 633139f Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 425b371fa1

ℹ️ 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".

raise RuntimeError(status["block_reason"] or "operation_in_progress")

ports = lan_access_port_candidates()
selected = _read_lan_access_addresses(strict = True)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Surface strict address-read failures in the LAN panel

When the saved lan_access_addresses row is malformed or its database read fails, this strict call raises lan_access_addresses_invalid/lan_access_addresses_unavailable before start_lan_listener can populate the listener error. The route converts that to a 409, but LanAccessSection.perform discards request errors for start, while the next non-strict status read reports Automatic and off; in this scenario clicking Start appears to do nothing, and Automatic is not dirty so it cannot be resaved directly. Preserve the 409 detail in the UI or publish this failure through status.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing: this needs a corrupt or unreadable settings row, which Studio never writes (the value is always json.dumps of a validated list or null). Start already fails closed with nothing bound, the saved port setting behaves the same way, and saving any choice from the picker overwrites the row.

Comment on lines +222 to +224
return (status?.availableAddresses ?? [])
.filter((entry) => !entry.public)
.map((entry) => entry.address);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Cap the default draft at the backend selection limit

On a host where detection returns more than 64 non-public addresses, switching from Automatic to Choose preselects all of them here, although the backend rejects any selection with more than _MAX_LAN_ACCESS_ADDRESSES (64) unique entries. Saving that untouched default therefore always gets a 422, and the component replaces the useful validation detail with the generic “Could not save” message, leaving the user to guess how many addresses to uncheck. Enforce or expose the same limit in the form before creating the default draft.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing: this needs a single host with more than 64 private IPv4 addresses detected on interfaces that are up. The backend still rejects it with a 422 and binds nothing, so nothing is exposed; it is outside the cases this setting is for.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 12, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 02f6ef0953

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: c9ee3898dd

ℹ️ 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".

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 12, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 12, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 633139ff35

ℹ️ 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".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

affects UI# edge case# new-feature# security# Moves a security boundary: sandbox, allowlist, permission or network guard

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Server always binds on all IP then warns about one being a public IP

2 participants