A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
Keep getpass responses out of saved console output (#11043)
Trevor Manzc6954f6ead3c
diff --git a/frontend/src/components/editor/output/console/ConsoleOutput.tsx b/frontend/src/components/editor/output/console/ConsoleOutput.tsxindex 6e6cb0ac0f..2293d7f8fe 100644--- a/frontend/src/components/editor/output/console/ConsoleOutput.tsx+++ b/frontend/src/components/editor/output/console/ConsoleOutput.tsx@@ -347,20 +347,20 @@ const StdInput = (props: {placeholder="stdin"// Capture the keydown event for history navigation and submissiononKeyDownCapture={(e) => {- if (e.key === "ArrowUp") {+ if (!isPassword && e.key === "ArrowUp") {navigateUp();e.preventDefault();return;}- if (e.key === "ArrowDown") {+ if (!isPassword && e.key === "ArrowDown") {navigateDown();e.preventDefault();return;}if (e.key === "Enter" && !e.shiftKey) {- if (value) {+ if (value && !isPassword) {addToHistory(value);}onSubmit(value);diff --git a/frontend/src/components/editor/output/console/__tests__/ConsoleOutput.test.tsx b/frontend/src/components/editor/output/console/__tests__/ConsoleOutput.test.tsxindex f58fa08ba4..a9719e7457 100644--- a/frontend/src/components/editor/output/console/__tests__/ConsoleOutput.test.tsx+++ b/frontend/src/components/editor/output/console/__tests__/ConsoleOutput.test.tsx@@ -120,6 +120,65 @@ describe("ConsoleOutput pdb history", () => {expect(newInput).toHaveValue("next");});+ it("submits passwords without making them available to input history", () => {+ const passwordPrompt: WithResponse<OutputMessage> = {+ ...stdinPrompt("Password: "),+ mimetype: "text/password",+ };+ const onSubmitDebugger = vi.fn();+ const { rerender } = renderWithProvider(+ <ConsoleOutput+ {...defaultProps}+ consoleOutputs={[stdinPrompt("Name: ")]}+ onSubmitDebugger={onSubmitDebugger}+ />,+ );+ const nameInput = screen.getByTestId("console-input");+ fireEvent.change(nameInput, { target: { value: "marimo" } });+ fireEvent.keyDown(nameInput, { key: "Enter" });++ rerender(+ <TooltipProvider>+ <ConsoleOutput+ {...defaultProps}+ consoleOutputs={[stdinPrompt("Name: ", "marimo"), passwordPrompt]}+ onSubmitDebugger={onSubmitDebugger}+ />+ </TooltipProvider>,+ );+ const input = screen.getByTestId("console-input");+ expect(input).toHaveAttribute("type", "password");+ fireEvent.change(input, { target: { value: "getpass-regression-secret" } });+ fireEvent.keyDown(input, { key: "ArrowUp" });+ expect(input).toHaveValue("getpass-regression-secret");+ fireEvent.keyDown(input, { key: "ArrowDown" });+ expect(input).toHaveValue("getpass-regression-secret");+ fireEvent.keyDown(input, { key: "Enter" });+ expect(onSubmitDebugger).toHaveBeenLastCalledWith(+ "getpass-regression-secret",+ 1,+ );+ expect(input).toHaveValue("");++ rerender(+ <TooltipProvider>+ <ConsoleOutput+ {...defaultProps}+ consoleOutputs={[+ stdinPrompt("Name: ", "marimo"),+ { ...passwordPrompt, response: "" },+ stdinPrompt("Name: "),+ ]}+ />+ </TooltipProvider>,+ );+ const nextInput = screen.getByTestId("console-input");+ fireEvent.keyDown(nextInput, { key: "ArrowUp" });+ expect(nextInput).toHaveValue("marimo");+ fireEvent.keyDown(nextInput, { key: "ArrowDown" });+ expect(nextInput).toHaveValue("");+ });+it("should submit an empty string when Enter is pressed with no input", () => {// Many CLIs prompt "Press Enter to continue" and expect "" back.const onSubmitDebugger = vi.fn();diff --git a/frontend/src/core/cells/__tests__/cells.test.ts b/frontend/src/core/cells/__tests__/cells.test.tsindex 40f6c2d797..4fdd58e5bd 100644--- a/frontend/src/core/cells/__tests__/cells.test.ts+++ b/frontend/src/core/cells/__tests__/cells.test.ts@@ -1504,6 +1504,33 @@ describe("cell reducer", () => {]);});+ it("resolves password prompts without retaining the response", () => {+ const prompt: OutputMessage = {+ channel: "stdin",+ mimetype: "text/password",+ data: "Password: ",+ timestamp: 1,+ };+ actions.handleCellMessage({+ cell_id: firstCellId,+ output: undefined,+ console: prompt,+ status: "running",+ stale_inputs: null,+ timestamp: 1 as Seconds,+ });++ const secret = "getpass-regression-secret";+ actions.setStdinResponse({+ cellId: firstCellId,+ outputIndex: 0,+ response: secret,+ });++ expect(cells[0].consoleOutputs).toEqual([{ ...prompt, response: "" }]);+ expect(JSON.stringify(cells[0].consoleOutputs)).not.toContain(secret);+ });+it("does not crash when setStdinResponse has out-of-bounds outputIndex", () => {const STDOUT: OutputMessage = {channel: "stdout",diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex 8f0bc96d21..ef4248a31b 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -1114,7 +1114,8 @@ const {mimetype: stdinOutput.mimetype,data: stdinOutput.data,timestamp: stdinOutput.timestamp,- response,+ // An empty response resolves the prompt without retaining the secret.+ response: stdinOutput.mimetype === "text/password" ? "" : response,};return {diff --git a/marimo/_session/state/serialize.py b/marimo/_session/state/serialize.pyindex 2988fba9da..bd62214843 100644--- a/marimo/_session/state/serialize.py+++ b/marimo/_session/state/serialize.py@@ -285,6 +285,9 @@ def deserialize_session(# Convert consoleconsole_outputs: list[CellOutput] = []for console in cell["console"]:+ # Older caches combined password prompts and responses in one string.+ if console.get("mimetype") == "text/password":+ continueif console["name"] == "media":console_outputs.append(CellOutput(diff --git a/marimo/_session/state/session_view.py b/marimo/_session/state/session_view.pyindex a490962957..f525d8b654 100644--- a/marimo/_session/state/session_view.py+++ b/marimo/_session/state/session_view.py@@ -290,7 +290,12 @@ class SessionView:for cell_output in console_outputs:if cell_output.channel == CellChannel.STDIN:cell_output.channel = CellChannel.STDOUT- cell_output.data = f"{cell_output.data} {stdin}\n"+ if cell_output.mimetype == "text/password":+ # This state is reused for replay, exports, and caches.+ cell_output.data = f"{cell_output.data}\n"+ cell_output.mimetype = "text/plain"+ else:+ cell_output.data = f"{cell_output.data} {stdin}\n"returndef add_notification(self, notification: NotificationMessage) -> None:diff --git a/tests/_export/test_exporter.py b/tests/_export/test_exporter.pyindex e30beb0122..7f818d273a 100644--- a/tests/_export/test_exporter.py+++ b/tests/_export/test_exporter.py@@ -596,6 +596,53 @@ def test_export_as_html_code_inclusion(assert text not in html+def test_export_as_html_omits_getpass_response(+ session_view: SessionView,+) -> None:+ app = App()++ @app.cell()+ def _():+ import getpass++ _password = getpass.getpass("Password: ")+ return++ internal_app = InternalApp(app)+ cell_id = next(iter(internal_app.cell_manager.cell_ids()))+ session_view.add_notification(+ CellNotification(+ cell_id=cell_id,+ console=CellOutput.stdin("Password: ", password=True),+ )+ )+ secret = "getpass-regression-secret"+ session_view.add_stdin(secret)++ html, _ = Exporter().export_as_html(+ _html_export_request(+ filename="getpass.py",+ app=internal_app,+ session_view=session_view,+ display_config=DEFAULT_CONFIG["display"],+ request=ExportAsHTMLRequest(+ download=False, files=[], include_code=True+ ),+ )+ )++ assert secret not in html+ assert secret not in encode_json_str(session_view.notifications)+ assert parse_mount_config(html)["session"]["cells"][0]["console"] == [+ {+ "type": "stream",+ "name": "stdout",+ "text": "Password: \n",+ "mimetype": "text/plain",+ }+ ]++def test_export_as_html_with_serialization(session_view: SessionView) -> None:"""Test HTML export uses new serialization approach correctly."""diff --git a/tests/_session/state/test_serialize_session.py b/tests/_session/state/test_serialize_session.pyindex c241ac7e7a..9bbcdd500a 100644--- a/tests/_session/state/test_serialize_session.py+++ b/tests/_session/state/test_serialize_session.py@@ -637,6 +637,47 @@ def test_deserialize_session_with_console():assert console_outputs[1].mimetype == "text/plain"+def test_deserialize_session_discards_cached_password_response():+ session = NotebookSessionV1(+ version="1",+ metadata={"marimo_version": "0.23.0"},+ cells=[+ {+ "id": "cell1",+ "code_hash": "123",+ "outputs": [],+ "console": [+ {+ "type": "stream",+ "name": "stdout",+ "text": "Password: cached-secret\n",+ "mimetype": "text/password",+ },+ {+ "type": "stream",+ "name": "stdout",+ "text": "Name: marimo\n",+ "mimetype": "text/plain",+ },+ ],+ }+ ],+ )++ view = deserialize_session(session, {"123": CELL1})+ restored = serialize_session_view(+ view, [CELL1], drop_virtual_file_outputs=True+ )+ assert restored["cells"][0]["console"] == [+ {+ "type": "stream",+ "name": "stdout",+ "text": "Name: marimo\n",+ "mimetype": "text/plain",+ }+ ]++async def test_session_cache_writer(session_view: SessionView):"""Test AsyncWriter writes session data periodically"""view = session_view