Skip to content

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.

12.9 KB
Raw Blame
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""Masked terminal password prompt: echo, editing, re-prompt validation and the should-prompt gate."""

from __future__ import annotations

import io
import sys
from pathlib import Path

import pytest

_BACKEND = Path(__file__).resolve().parents[1]
if str(_BACKEND) not in sys.path:
    sys.path.insert(0, str(_BACKEND))

from auth import terminal_prompt as tp  # noqa: E402


def _fake_getch(keys):
    """Yields one key per _getch() call; a multi-char item is a paste burst in one read."""
    it = iter(keys)

    def getch():
        return next(it)

    return getch


def _read(
    monkeypatch,
    keys,
    prompt = "P: ",
):
    monkeypatch.setattr(tp, "_getch", _fake_getch(keys))
    out = io.StringIO()
    value = tp._read_password(prompt, out = out)
    return value, out.getvalue()


def test_reader_echoes_one_star_per_char(monkeypatch):
    value, out = _read(monkeypatch, list("secret") + ["\r"])
    assert value == "secret"
    assert out.count("*") == 6
    assert "secret" not in out


def test_reader_backspace_edits_and_erases_star(monkeypatch):
    value, out = _read(monkeypatch, list("abc") + ["\x7f"] + list("d") + ["\n"])
    assert value == "abd"
    assert "\b \b" in out
    assert out.count("*") == 4


def test_reader_backspace_on_empty_buffer_is_noop(monkeypatch):
    value, out = _read(monkeypatch, ["\x08", "\x7f"] + list("x") + ["\r"])
    assert value == "x"
    assert "\b \b" not in out


def test_reader_paste_burst_delivers_all_chars(monkeypatch):
    value, out = _read(monkeypatch, ["pasted-secret", "\r"])
    assert value == "pasted-secret"
    assert out.count("*") == len("pasted-secret")


def test_reader_unicode_password(monkeypatch):
    value, _ = _read(monkeypatch, list("pässwörd✓") + ["\r"])
    assert value == "pässwörd✓"


def test_reader_ignores_other_control_chars(monkeypatch):
    value, _ = _read(monkeypatch, ["\t", "\x1b"] + list("ok") + ["\r"])
    assert value == "ok"


def test_reader_ctrl_c_raises_keyboard_interrupt(monkeypatch):
    monkeypatch.setattr(tp, "_getch", _fake_getch(list("ab") + ["\x03"]))
    with pytest.raises(KeyboardInterrupt):
        tp._read_password("P: ", out = io.StringIO())


def test_reader_ctrl_d_on_empty_raises_eof(monkeypatch):
    monkeypatch.setattr(tp, "_getch", _fake_getch(["\x04"]))
    with pytest.raises(EOFError):
        tp._read_password("P: ", out = io.StringIO())


def test_reader_ctrl_d_mid_input_is_ignored(monkeypatch):
    value, _ = _read(monkeypatch, list("ab") + ["\x04"] + list("c") + ["\r"])
    assert value == "abc"


def test_reader_windows_key_prefix_is_ignored(monkeypatch):
    # _getch_windows reports swallowed function-key sequences as "\x00".
    value, _ = _read(monkeypatch, ["\x00"] + list("w") + ["\r"])
    assert value == "w"


def test_reader_holds_raw_mode_once_for_whole_line(monkeypatch):
    # cbreak/no-echo must span the whole line: toggling per key echoes keystrokes in the gap.
    events = []

    class _SpyRawMode:
        def __enter__(self):
            events.append("enter")
            return self

        def __exit__(self, *exc):
            events.append("exit")
            return False

    monkeypatch.setattr(tp, "_prompt_raw_mode", _SpyRawMode)

    src = _fake_getch(list("s3cr3t!!") + ["\r"])

    def _getch_recording():
        assert events and events[-1] == "enter", "keystroke read outside raw mode"
        return src()

    monkeypatch.setattr(tp, "_getch", _getch_recording)
    value = tp._read_password("P: ", out = io.StringIO())
    assert value == "s3cr3t!!"
    assert events == ["enter", "exit"]


def _run_loop(
    monkeypatch,
    keys,
    *,
    min_length = 8,
    current = "bootstrap-pw",
):
    monkeypatch.setattr(tp, "_getch", _fake_getch(keys))
    out = io.StringIO()
    applied = []
    ok = tp.prompt_for_password_change(
        min_length = min_length,
        is_current_password = lambda pw: pw == current,
        apply_change = applied.append,
        out = out,
    )
    return ok, applied, out.getvalue()


def _keys(*lines):
    keys = []
    for line in lines:
        keys.extend(list(line))
        keys.append("\r")
    return keys


def test_loop_success_applies_once(monkeypatch):
    ok, applied, out = _run_loop(monkeypatch, _keys("new-password", "new-password"))
    assert ok is True
    assert applied == ["new-password"]
    assert "Password updated" in out
    assert "new-password" not in out


@pytest.mark.parametrize(
    "first, second, third, expected_applied, expected_message",
    [
        pytest.param(
            "short",
            "long-enough-pw",
            "long-enough-pw",
            "long-enough-pw",
            "at least 8 characters",
            id = "loop_short_password_reprompts",
        ),
        pytest.param(
            "has space pw",
            "long-enough-pw",
            "long-enough-pw",
            "long-enough-pw",
            "contain spaces",
            id = "loop_password_with_inner_space_reprompts",
        ),
        pytest.param(
            "bootstrap-pw",
            "fresh-password",
            "fresh-password",
            "fresh-password",
            "must differ",
            id = "loop_rejects_current_password",
        ),
    ],
)
def test_prompt_loop_reprompts_until_the_password_is_acceptable(
    monkeypatch, first, second, third, expected_applied, expected_message
):
    ok, applied, out = _run_loop(monkeypatch, _keys(first, second, third))
    assert ok is True
    assert applied == [expected_applied]
    assert expected_message in out


def test_loop_whitespace_only_reprompts(monkeypatch):
    ok, applied, out = _run_loop(monkeypatch, _keys(" " * 8, "long-enough-pw", "long-enough-pw"))
    assert ok is True
    assert applied == ["long-enough-pw"]
    assert "contain spaces" in out


def test_loop_mismatch_reprompts_then_succeeds(monkeypatch):
    ok, applied, out = _run_loop(
        monkeypatch,
        _keys("first-attempt", "typo-attempt", "second-attempt", "second-attempt"),
    )
    assert ok is True
    assert applied == ["second-attempt"]
    assert "do not match" in out


def test_loop_ctrl_c_aborts_without_applying(monkeypatch):
    ok, applied, out = _run_loop(monkeypatch, list("ab") + ["\x03"])
    assert ok is False
    assert applied == []
    assert "aborted" in out


def test_loop_eof_aborts_without_applying(monkeypatch):
    ok, applied, out = _run_loop(monkeypatch, ["\x04"])
    assert ok is False
    assert applied == []
    assert "aborted" in out


def test_loop_ctrl_c_at_confirmation_aborts(monkeypatch):
    ok, applied, _ = _run_loop(monkeypatch, _keys("valid-password") + ["\x03"])
    assert ok is False
    assert applied == []


def test_loop_min_length_counts_code_points(monkeypatch):
    pw = "pässwörd"
    assert len(pw) == 8
    ok, applied, _ = _run_loop(monkeypatch, _keys(pw, pw))
    assert ok is True
    assert applied == [pw]


@pytest.mark.parametrize(
    "tunnel,requires,stdin_tty,stderr_tty,expected",
    [
        (True, True, True, True, True),
        (False, True, True, True, False),
        (True, False, True, True, False),
        (True, True, False, True, False),
        (True, True, True, False, False),
        (False, False, False, False, False),
    ],
)
def test_should_prompt_matrix(tunnel, requires, stdin_tty, stderr_tty, expected):
    assert (
        tp.should_prompt_password_change(
            tunnel_will_start = tunnel,
            requires_change = requires,
            stdin_isatty = stdin_tty,
            stderr_isatty = stderr_tty,
        )
        is expected
    )


def test_stream_eof_aborts_instead_of_submitting(monkeypatch):
    # A dead stream ('' from _getch) must abort, never submit the partial password.
    import io

    err = io.StringIO()
    monkeypatch.setattr(tp, "_getch", _fake_getch(list("abc") + [""]))
    with pytest.raises(EOFError):
        tp._read_password("New password: ", out = err)


def test_resolve_supplied_password_literal_value_and_note(monkeypatch):
    import io

    monkeypatch.delenv(tp.SUPPLIED_PASSWORD_ENV, raising = False)
    out = io.StringIO()
    assert tp.resolve_supplied_password("hunter2pw", out = out) == "hunter2pw"
    assert "process list" in out.getvalue()


def test_resolve_supplied_password_stdin(monkeypatch):
    import io

    monkeypatch.delenv(tp.SUPPLIED_PASSWORD_ENV, raising = False)
    monkeypatch.setattr(sys, "stdin", io.StringIO("from-stdin-pw\n"))
    assert tp.resolve_supplied_password("-") == "from-stdin-pw"


def test_resolve_supplied_password_stdin_empty_is_none(monkeypatch):
    import io

    monkeypatch.delenv(tp.SUPPLIED_PASSWORD_ENV, raising = False)
    monkeypatch.setattr(sys, "stdin", io.StringIO(""))
    assert tp.resolve_supplied_password("-") is None


def test_resolve_supplied_password_env(monkeypatch):
    monkeypatch.setenv(tp.SUPPLIED_PASSWORD_ENV, "env-secret-pw")
    assert tp.resolve_supplied_password("") == "env-secret-pw"
    assert tp.resolve_supplied_password(None) == "env-secret-pw"


def test_resolve_supplied_password_literal_beats_env(monkeypatch):
    import io
    monkeypatch.setenv(tp.SUPPLIED_PASSWORD_ENV, "env-secret-pw")
    assert tp.resolve_supplied_password("cli-wins-pw", out = io.StringIO()) == "cli-wins-pw"


def test_resolve_supplied_password_stdin_beats_env(monkeypatch):
    # `--password -` reads stdin and short-circuits, so a set env var does not win.
    import io

    monkeypatch.setenv(tp.SUPPLIED_PASSWORD_ENV, "env-secret-pw")
    monkeypatch.setattr(sys, "stdin", io.StringIO("stdin-wins-pw\n"))
    assert tp.resolve_supplied_password("-") == "stdin-wins-pw"


def test_resolve_supplied_password_off_by_default(monkeypatch):
    monkeypatch.delenv(tp.SUPPLIED_PASSWORD_ENV, raising = False)
    assert tp.resolve_supplied_password("") is None
    assert tp.resolve_supplied_password(None) is None


# A raw non-loopback bind (-H 0.0.0.0) is exposure too, even without a tunnel.


def test_a_raw_exposed_bind_prompts_when_a_terminal_is_attached():
    from auth.terminal_prompt import should_prompt_password_change
    assert (
        should_prompt_password_change(
            tunnel_will_start = False,
            bind_is_exposed = True,
            requires_change = True,
            stdin_isatty = True,
            stderr_isatty = True,
        )
        is True
    )


def test_a_raw_exposed_bind_stays_silent_without_a_terminal():
    """Headless raw binds stay silent and keep their deadline; downstream logic assumes a public URL."""
    from auth.terminal_prompt import should_prompt_password_change
    for stdin_tty, stderr_tty in ((False, False), (True, False), (False, True)):
        assert (
            should_prompt_password_change(
                tunnel_will_start = False,
                bind_is_exposed = True,
                requires_change = True,
                stdin_isatty = stdin_tty,
                stderr_isatty = stderr_tty,
            )
            is False
        )


def test_a_loopback_launch_is_untouched():
    """Plain `unsloth studio` must be completely unaffected."""
    from auth.terminal_prompt import should_prompt_password_change
    assert (
        should_prompt_password_change(
            tunnel_will_start = False,
            bind_is_exposed = False,
            requires_change = True,
            stdin_isatty = True,
            stderr_isatty = True,
        )
        is False
    )


def test_an_already_changed_password_never_prompts():
    from auth.terminal_prompt import should_prompt_password_change
    assert (
        should_prompt_password_change(
            tunnel_will_start = True,
            bind_is_exposed = True,
            requires_change = False,
            stdin_isatty = True,
            stderr_isatty = True,
        )
        is False
    )


def test_the_default_keeps_old_callers_tunnel_only():
    """bind_is_exposed defaults False, so an old caller behaves as before."""
    from auth.terminal_prompt import should_prompt_password_change
    assert (
        should_prompt_password_change(
            tunnel_will_start = False,
            requires_change = True,
            stdin_isatty = True,
            stderr_isatty = True,
        )
        is False
    )


def test_the_prompt_banner_does_not_claim_the_internet_for_a_lan_bind(monkeypatch):
    """A LAN bind is not the public internet; saying so falsely trains people to ignore the banner."""
    import io

    from auth import terminal_prompt

    def _no_input(*_a, **_k):
        raise EOFError

    monkeypatch.setattr(terminal_prompt, "_read_password", _no_input)

    out = io.StringIO()
    # The read aborts immediately; fine, the banner is written before any read.
    terminal_prompt.prompt_for_password_change(
        min_length = 8,
        is_current_password = lambda _c: False,
        apply_change = lambda _p: None,
        out = out,
        exposure = "on every network interface",
    )
    text = out.getvalue()
    assert "on every network interface" in text
    assert "public internet" not in text