Skip to content

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.

Mask `getpass.getpass()` input in notebook UI (#8345)

Trevor Manz862d35ec9ec9
diff --git a/frontend/src/components/editor/Output.tsx b/frontend/src/components/editor/Output.tsx
index c1a584683b..1b3535c7e9 100644
--- a/frontend/src/components/editor/Output.tsx
+++ b/frontend/src/components/editor/Output.tsx
@@ -123,6 +123,7 @@ export const OutputRenderer: React.FC<{
);
case "text/plain":
+ case "text/password":
invariant(
typeof data === "string",
`Expected string data for mime=${mimetype}. Got ${typeof data}`,
diff --git a/frontend/src/components/editor/output/console/ConsoleOutput.tsx b/frontend/src/components/editor/output/console/ConsoleOutput.tsx
index 6da1bd788e..adf3987f1a 100644
--- a/frontend/src/components/editor/output/console/ConsoleOutput.tsx
+++ b/frontend/src/components/editor/output/console/ConsoleOutput.tsx
@@ -167,6 +167,7 @@ const ConsoleOutputInternal = (props: Props): React.ReactNode => {
);
const originalIdx = consoleOutputs.length - idx - 1;
+ const isPassword = output.mimetype === "text/password";
if (output.response == null && lastStdInputIdx === idx) {
return (
@@ -174,6 +175,7 @@ const ConsoleOutputInternal = (props: Props): React.ReactNode => {
key={idx}
output={output.data}
isPdb={isPdb}
+ isPassword={isPassword}
onSubmit={(text) => onSubmitDebugger(text, originalIdx)}
onClear={onClear}
/>
@@ -185,6 +187,7 @@ const ConsoleOutputInternal = (props: Props): React.ReactNode => {
key={idx}
output={output.data}
response={output.response}
+ isPassword={isPassword}
/>
);
}
@@ -216,6 +219,7 @@ const StdInput = (props: {
output: string;
response?: string;
isPdb: boolean;
+ isPassword?: boolean;
}) => {
const [value, setValue] = React.useState("");
@@ -231,7 +235,7 @@ const StdInput = (props: {
data-testid="console-input"
// This is used in <StdinBlockingAlert> to find the input
data-stdin-blocking={true}
- type="text"
+ type={props.isPassword ? "password" : "text"}
autoComplete="off"
autoFocus={true}
value={value}
@@ -277,11 +281,17 @@ const StdInput = (props: {
);
};
-const StdInputWithResponse = (props: { output: string; response?: string }) => {
+const StdInputWithResponse = (props: {
+ output: string;
+ response?: string;
+ isPassword?: boolean;
+}) => {
return (
<div className="flex gap-2 items-center">
{renderText(props.output)}
- <span className="text-(--sky-11)">{props.response}</span>
+ {!props.isPassword && (
+ <span className="text-(--sky-11)">{props.response}</span>
+ )}
</div>
);
};
diff --git a/marimo/_messaging/cell_output.py b/marimo/_messaging/cell_output.py
index 16cf20deb9..5fcc8e157c 100644
--- a/marimo/_messaging/cell_output.py
+++ b/marimo/_messaging/cell_output.py
@@ -63,9 +63,11 @@ class CellOutput(msgspec.Struct):
)
@staticmethod
- def stdin(data: str) -> CellOutput:
+ def stdin(data: str, password: bool = False) -> CellOutput:
return CellOutput(
- channel=CellChannel.STDIN, mimetype="text/plain", data=data
+ channel=CellChannel.STDIN,
+ mimetype="text/password" if password else "text/plain",
+ data=data,
)
@staticmethod
diff --git a/marimo/_messaging/mimetypes.py b/marimo/_messaging/mimetypes.py
index 85c38d9cbc..c40a03c861 100644
--- a/marimo/_messaging/mimetypes.py
+++ b/marimo/_messaging/mimetypes.py
@@ -4,8 +4,12 @@ from __future__ import annotations
from typing import Any, Literal, Union
# It is convenient to write mimetypes as strings,
-# but can lead to typos. This literal type
-# helps us avoid typos.
+# but can lead to typos. This literal type helps
+# us avoid typos.
+#
+# While nonstandard MIME types are often given an
+# `x-` prefix our non IAIA types to not follow
+# this convention (e.g., text/password, text/latex).
KnownMimeType = Literal[
"application/json",
"application/vnd.marimo+error",
@@ -27,6 +31,7 @@ KnownMimeType = Literal[
"video/mpeg",
"text/html",
"text/plain",
+ "text/password",
"text/markdown",
"text/latex",
"text/csv",
@@ -35,6 +40,7 @@ KnownMimeType = Literal[
ConsoleMimeType = Literal[
"application/vnd.marimo+traceback",
"text/plain",
+ "text/password",
"image/png",
]
diff --git a/marimo/_messaging/streams.py b/marimo/_messaging/streams.py
index 23c16b2c84..b49511dfe2 100644
--- a/marimo/_messaging/streams.py
+++ b/marimo/_messaging/streams.py
@@ -361,7 +361,9 @@ class ThreadSafeStdin(Stdin):
def readable(self) -> bool:
return True
- def _readline_with_prompt(self, prompt: str = "") -> str:
+ def _readline_with_prompt(
+ self, prompt: str = "", password: bool = False
+ ) -> str:
"""Read input from the standard in stream, with an optional prompt."""
assert self._stream.cell_id is not None
if not isinstance(prompt, str):
@@ -377,6 +379,9 @@ class ThreadSafeStdin(Stdin):
+ " ... "
)
+ mimetype: ConsoleMimeType = (
+ "text/password" if password else "text/plain"
+ )
with self._stream.console_msg_cv:
# This sends a prompt request to the frontend.
self._stream.console_msg_queue.append(
@@ -384,7 +389,7 @@ class ThreadSafeStdin(Stdin):
stream=CellChannel.STDIN,
cell_id=self._stream.cell_id,
data=prompt,
- mimetype="text/plain",
+ mimetype=mimetype,
)
)
self._stream.console_msg_cv.notify()
diff --git a/marimo/_pyodide/streams.py b/marimo/_pyodide/streams.py
index ab9fe4c444..7a53b11f76 100644
--- a/marimo/_pyodide/streams.py
+++ b/marimo/_pyodide/streams.py
@@ -149,7 +149,9 @@ class PyodideStdin(Stdin):
def readable(self) -> bool:
return True
- def _readline_with_prompt(self, prompt: str = "") -> str:
+ def _readline_with_prompt(
+ self, prompt: str = "", password: bool = False
+ ) -> str:
"""Read input from the standard in stream, with an optional prompt."""
assert self.stream.cell_id is not None
if not isinstance(prompt, str):
@@ -167,7 +169,7 @@ class PyodideStdin(Stdin):
broadcast_notification(
CellNotification(
cell_id=self.stream.cell_id,
- console=CellOutput.stdin(prompt),
+ console=CellOutput.stdin(prompt, password=password),
),
self.stream,
)
diff --git a/marimo/_runtime/input_override.py b/marimo/_runtime/input_override.py
index 6b7eac34c7..2c41c06ed1 100644
--- a/marimo/_runtime/input_override.py
+++ b/marimo/_runtime/input_override.py
@@ -3,9 +3,20 @@ from __future__ import annotations
import functools
import sys
+from typing import Any
@functools.wraps(input)
def input_override(prompt: str = "") -> str:
# sys.stdin is overridden
return sys.stdin._readline_with_prompt(prompt) # type: ignore[attr-defined, no-any-return, union-attr] # noqa: E501
+
+
+def getpass_override(prompt: str = "Password: ", stream: Any = None) -> str:
+ """Override for getpass.getpass that routes through marimo's stdin.
+
+ The stream parameter is accepted for API compatibility but ignored,
+ matching ipykernel's behavior.
+ """
+ del stream
+ return sys.stdin._readline_with_prompt(prompt, password=True) # type: ignore[attr-defined, no-any-return, union-attr] # noqa: E501
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 8af62b014f..c6d168fae1 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -144,7 +144,7 @@ from marimo._runtime.context.kernel_context import (
)
from marimo._runtime.context.types import teardown_context
from marimo._runtime.control_flow import MarimoInterrupt
-from marimo._runtime.input_override import input_override
+from marimo._runtime.input_override import getpass_override, input_override
from marimo._runtime.packages.import_error_extractors import (
extract_missing_module_from_cause_chain,
try_extract_packages_from_import_error_message,
@@ -612,6 +612,12 @@ class Kernel:
# was invoked. New state updates evict older ones.
self.state_updates: dict[State[Any], CellId_t] = {}
+ # Override getpass.getpass to route through marimo's stdin with
+ # password masking, instead of trying /dev/tty or falling back
+ # to plaintext with warnings.
+ import getpass
+
+ getpass.getpass = getpass_override
# Webbrowser may not be set (e.g. docker container) or stubbed/broken
# (e.g. in pyodide). Set default to just inject an iframe of the
# expected page to output.
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index 26808828d3..16670c5fa0 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -489,6 +489,7 @@ components:
- text/html
- text/latex
- text/markdown
+ - text/password
- text/plain
- video/mp4
- video/mpeg
@@ -4571,6 +4572,7 @@ components:
- text/html
- text/latex
- text/markdown
+ - text/password
- text/plain
- video/mp4
- video/mpeg
@@ -4938,7 +4940,7 @@ components:
type: object
info:
title: marimo API
- version: 0.19.10
+ version: 0.19.11
openapi: 3.1.0
paths:
/@file/{filename_and_length}:
@@ -6311,3 +6313,4 @@ paths:
summary: Submit login form
tags:
- auth
+
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index 867900cfbe..57bbe72202 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -3387,6 +3387,7 @@ export interface components {
| "text/html"
| "text/latex"
| "text/markdown"
+ | "text/password"
| "text/plain"
| "video/mp4"
| "video/mpeg";
@@ -5830,6 +5831,7 @@ export interface components {
| "text/html"
| "text/latex"
| "text/markdown"
+ | "text/password"
| "text/plain"
| "video/mp4"
| "video/mpeg"
diff --git a/tests/_messaging/test_cell_output.py b/tests/_messaging/test_cell_output.py
index f304760ac4..6372623635 100644
--- a/tests/_messaging/test_cell_output.py
+++ b/tests/_messaging/test_cell_output.py
@@ -117,6 +117,12 @@ def test_cell_output_static_methods():
assert stdin.mimetype == "text/plain"
assert stdin.data == "User input"
+ # Test stdin password method
+ stdin_pw = CellOutput.stdin("Enter password", password=True)
+ assert stdin_pw.channel == CellChannel.STDIN
+ assert stdin_pw.mimetype == "text/password"
+ assert stdin_pw.data == "Enter password"
+
# Test errors method
errors = CellOutput.errors([MarimoSyntaxError(msg="Test error")])
assert errors.channel == CellChannel.MARIMO_ERROR
diff --git a/tests/_messaging/test_streams.py b/tests/_messaging/test_streams.py
index a16551df61..40f5e97b58 100644
--- a/tests/_messaging/test_streams.py
+++ b/tests/_messaging/test_streams.py
@@ -36,6 +36,15 @@ class TestStdin:
)
assert k.globals["output"] == [""]
+ @staticmethod
+ async def test_getpass_installed(
+ k: Kernel, exec_req: ExecReqProvider
+ ) -> None:
+ await k.run(
+ [exec_req.get("import getpass; output = getpass.getpass('pwd: ')")]
+ )
+ assert k.globals["output"] == "pwd: "
+
class TestStdout:
@staticmethod
diff --git a/tests/conftest.py b/tests/conftest.py
index 13e56da1f2..ac410602e9 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -171,7 +171,10 @@ class MockStdin(ThreadSafeStdin):
super().__init__(stream)
self.messages: list[str] = []
- def _readline_with_prompt(self, prompt: str = "") -> str:
+ def _readline_with_prompt(
+ self, prompt: str = "", password: bool = False
+ ) -> str:
+ del password
return prompt