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
fix: sanitize password in frontend render (#8857)
Dylan Madisetti4c25414686eb
diff --git a/frontend/src/plugins/impl/TextInputPlugin.tsx b/frontend/src/plugins/impl/TextInputPlugin.tsxindex d82dbff79e..599c9776f5 100644--- a/frontend/src/plugins/impl/TextInputPlugin.tsx+++ b/frontend/src/plugins/impl/TextInputPlugin.tsx@@ -1,13 +1,14 @@/* Copyright 2026 Marimo. All rights reserved. */import { AtSignIcon, GlobeIcon, LockIcon } from "lucide-react";-import { type JSX, useState } from "react";+import { type JSX, useRef, useState } from "react";import { z } from "zod";import {DebouncedInput,Input,OnBlurredInput,} from "../../components/ui/input";+import { RANDOM_ID_ATTR } from "../../core/dom/ui-element-constants";import { cn } from "../../utils/cn";import type { IPlugin, IPluginProps, Setter } from "../types";import { Labeled } from "./common/labeled";@@ -25,8 +26,12 @@ interface Data {disabled?: boolean;debounce?: boolean | number;fullWidth: boolean;+ passwordHasValue?: boolean;}+// Matches the masked dots.+const MASK_PLACEHOLDER = "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022";+export class TextInputPlugin implements IPlugin<T, Data> {tagName = "marimo-text";@@ -40,11 +45,20 @@ export class TextInputPlugin implements IPlugin<T, Data> {fullWidth: z.boolean().default(false),disabled: z.boolean().optional(),debounce: z.optional(z.union([z.boolean(), z.number()])),+ passwordHasValue: z.boolean().optional(),});render(props: IPluginProps<T, Data>): JSX.Element {+ // Force remount on cell re-run so masked state resets cleanly+ const remountKey =+ props.data.kind === "password"+ ? props.host+ .closest(`[${RANDOM_ID_ATTR}]`)+ ?.getAttribute(RANDOM_ID_ATTR)+ : undefined;return (<TextComponent+ key={remountKey ?? undefined}{...props.data}value={props.value}setValue={props.setValue}@@ -59,9 +73,33 @@ interface TextComponentProps extends Data {}const TextComponent = (props: TextComponentProps) => {- const [valueOnBlur, setValueOnBlur] = useState(props.value);+ // Before first real keystroke: show masked placeholder, suppress setValue.+ // After first keystroke: normal password field.+ const initiallyMasked =+ props.kind === "password" && props.passwordHasValue === true;+ const [masked, setMasked] = useState(initiallyMasked);+ const hasTyped = useRef(false);++ const value = masked ? "" : props.value;+ const placeholder = masked ? MASK_PLACEHOLDER : props.placeholder;+ const setValue: Setter<T> = masked+ ? (v) => {+ if (!hasTyped.current) {+ return;+ }+ setMasked(false);+ props.setValue(v);+ }+ : props.setValue;+ // Capture-phase handler sets the ref synchronously before child onChange+ const onInputCapture = masked+ ? () => {+ hasTyped.current = true;+ }+ : undefined;- const valueToValidate = valueOnBlur == null ? props.value : valueOnBlur;+ const [valueOnBlur, setValueOnBlur] = useState(props.value);+ const valueToValidate = valueOnBlur == null ? value : valueOnBlur;const isValid = validate(props.kind, valueToValidate);const icon: Record<InputType, JSX.Element | null> = {@@ -73,80 +111,79 @@ const TextComponent = (props: TextComponentProps) => {const endAdornment = props.maxLength ? (<span className="text-muted-foreground text-xs font-medium">- {props.value.length}/{props.maxLength}+ {value.length}/{props.maxLength}</span>) : null;+ const inputClassName = cn({+ "border-destructive": !isValid,+ "w-full": props.fullWidth,+ });++ let input: JSX.Element;+if (props.debounce === true) {- return (- <Labeled label={props.label} fullWidth={props.fullWidth}>- <OnBlurredInput- data-testid="marimo-plugin-text-input"- type={props.kind}- icon={icon[props.kind]}- placeholder={props.placeholder}- maxLength={props.maxLength}- minLength={props.minLength}- required={props.minLength != null && props.minLength > 0}- disabled={props.disabled}- className={cn({- "border-destructive": !isValid,- "w-full": props.fullWidth,- })}- endAdornment={endAdornment}- value={props.value}- onValueChange={props.setValue}- />- </Labeled>+ input = (+ <OnBlurredInput+ data-testid="marimo-plugin-text-input"+ type={props.kind}+ icon={icon[props.kind]}+ placeholder={placeholder}+ maxLength={props.maxLength}+ minLength={props.minLength}+ required={props.minLength != null && props.minLength > 0}+ disabled={props.disabled}+ className={inputClassName}+ endAdornment={endAdornment}+ value={value}+ onValueChange={setValue}+ onInputCapture={onInputCapture}+ />);- }-- if (typeof props.debounce === "number") {- return (- <Labeled label={props.label} fullWidth={props.fullWidth}>- <DebouncedInput- data-testid="marimo-plugin-text-input"- type={props.kind}- icon={icon[props.kind]}- placeholder={props.placeholder}- maxLength={props.maxLength}- minLength={props.minLength}- required={props.minLength != null && props.minLength > 0}- disabled={props.disabled}- className={cn({- "border-destructive": !isValid,- "w-full": props.fullWidth,- })}- endAdornment={endAdornment}- value={props.value}- onValueChange={props.setValue}- onBlur={(event) => setValueOnBlur(event.currentTarget.value)}- delay={props.debounce}- />- </Labeled>+ } else if (typeof props.debounce === "number") {+ input = (+ <DebouncedInput+ data-testid="marimo-plugin-text-input"+ type={props.kind}+ icon={icon[props.kind]}+ placeholder={placeholder}+ maxLength={props.maxLength}+ minLength={props.minLength}+ required={props.minLength != null && props.minLength > 0}+ disabled={props.disabled}+ className={inputClassName}+ endAdornment={endAdornment}+ value={value}+ onValueChange={setValue}+ onBlur={(event) => setValueOnBlur(event.currentTarget.value)}+ delay={props.debounce}+ onInputCapture={onInputCapture}+ />);- }-- return (- <Labeled label={props.label} fullWidth={props.fullWidth}>+ } else {+ input = (<Inputdata-testid="marimo-plugin-text-input"type={props.kind}icon={icon[props.kind]}- placeholder={props.placeholder}+ placeholder={placeholder}maxLength={props.maxLength}minLength={props.minLength}required={props.minLength != null && props.minLength > 0}disabled={props.disabled}- className={cn({- "border-destructive": !isValid,- "w-full": props.fullWidth,- })}+ className={inputClassName}endAdornment={endAdornment}- value={props.value}- onInput={(event) => props.setValue(event.currentTarget.value)}+ value={value}+ onInput={(event) => setValue(event.currentTarget.value)}onBlur={(event) => setValueOnBlur(event.currentTarget.value)}+ onInputCapture={onInputCapture}/>+ );+ }++ return (+ <Labeled label={props.label} fullWidth={props.fullWidth}>+ {input}</Labeled>);};diff --git a/marimo/_plugins/ui/_core/ui_element.py b/marimo/_plugins/ui/_core/ui_element.pyindex 13d73236b5..9113804bea 100644--- a/marimo/_plugins/ui/_core/ui_element.py+++ b/marimo/_plugins/ui/_core/ui_element.py@@ -268,15 +268,16 @@ class UIElement(Html, Generic[S, T]):self._ctx.function_registry.register(namespace=self._id, function=function)- self._initial_value_frontend = initial_value- self._value_frontend = initial_value+ frontend_value = self._frontend_initial_value(initial_value)+ self._initial_value_frontend = frontend_value+ self._value_frontend = frontend_valueself._value = self._initial_value = self._convert_value(initial_value)self._on_change = on_changeself._component_args = argsself._inner_text = build_ui_plugin(component_name,- initial_value,+ frontend_value,label,args,slotted_html,@@ -298,6 +299,14 @@ class UIElement(Html, Generic[S, T]):"""pass+ def _frontend_initial_value(self, value: S) -> S:+ """Return the initial value to embed in HTML sent to the frontend.++ Override to sanitize the value for HTML rendering (e.g. masking+ passwords) while keeping the real value for Python-side state.+ """+ return value+def _register_as_view(self, parent: UIElement[Any, Any], key: str) -> None:"""Register this element as a view of `parent`."""self._lens = Lens(parent_id=parent._id, key=key)diff --git a/marimo/_plugins/ui/_impl/input.py b/marimo/_plugins/ui/_impl/input.pyindex 1301214f5a..6009e8ad09 100644--- a/marimo/_plugins/ui/_impl/input.py+++ b/marimo/_plugins/ui/_impl/input.py@@ -753,6 +753,7 @@ class text(UIElement[str, str]):on_change: Optional[Callable[[str], None]] = None,full_width: bool = False,) -> None:+ self._masked: bool = kind == "password" and bool(value)super().__init__(component_name=text._name,initial_value=value,@@ -764,10 +765,27 @@ class text(UIElement[str, str]):"full-width": full_width,"disabled": disabled,"debounce": debounce,+ "password-has-value": self._masked or None,},on_change=on_change,)+ def _frontend_initial_value(self, value: str) -> str:+ if self._masked:+ return ""+ return value++ def _update(self, value: str) -> None:+ # While the frontend is in masked state it sends "" (user never typed).+ # Ignore that to preserve the real backend password. Once the user+ # sends a non-empty value we unmask, so a subsequent "" (intentional+ # clear) is accepted normally.+ if self._masked:+ if value == "":+ return+ self._masked = False+ super()._update(value)+def _convert_value(self, value: str) -> str:return valuediff --git a/marimo/_smoke_tests/inputs/password_masking.py b/marimo/_smoke_tests/inputs/password_masking.pynew file mode 100644index 0000000000..e400196962--- /dev/null+++ b/marimo/_smoke_tests/inputs/password_masking.py@@ -0,0 +1,112 @@+import marimo++__generated_with = "0.21.1"+app = marimo.App(width="medium")+++def _():+ import marimo as mo++ return (mo,)+++def _(mo):+ mo.md("""+ ## Password Masking Test (MO-5366)+ """)+ return+++def _(mo):+ pw_debounce_true = mo.ui.text(+ kind="password",+ value="secret-B",+ label="debounce=True (default, on blur)",+ debounce=True,+ )+ pw_debounce_true+ return (pw_debounce_true,)+++def _(pw_debounce_true):+ print(f"debounce=True value: {pw_debounce_true.value!r}")+ return+++def _(mo):+ pw_debounce_num = mo.ui.text(+ kind="password",+ value="secret-C",+ label="debounce=300 (300ms delay)",+ debounce=300,+ )+ pw_debounce_num+ return (pw_debounce_num,)+++def _(pw_debounce_num):+ print(f"debounce=300 value: {pw_debounce_num.value!r}")+ return+++def _(mo):+ pw_debounce_false = mo.ui.text(+ kind="password",+ value="secret-C",+ label="debounce=False (immediate)",+ debounce=False,+ )+ pw_debounce_false+ return (pw_debounce_false,)+++def _(pw_debounce_false):+ print(f"debounce=False value: {pw_debounce_false.value!r}")+ return+++def _(mo):+ pw_empty = mo.ui.text(+ kind="password",+ placeholder="No initial value...",+ label="Password (no initial value)",+ )+ pw_empty+ return (pw_empty,)+++def _(pw_empty):+ print(f"Empty password value: {pw_empty.value!r}")+ return+++def _(mo):+ pw_form = mo.ui.text(+ kind="password",+ value="secret-B",+ placeholder="With initial value...",+ label="Password",+ ).form()+ pw_form+ return (pw_form,)+++def _(pw_form):+ print(f"Form password value: {pw_form.value!r}")+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_plugins/ui/_impl/test_input.py b/tests/_plugins/ui/_impl/test_input.pyindex 6caf8f47f4..8071762361 100644--- a/tests/_plugins/ui/_impl/test_input.py+++ b/tests/_plugins/ui/_impl/test_input.py@@ -291,6 +291,75 @@ def test_text() -> None:assert text.value == "value"+def test_text_password_masking() -> None:+ from marimo._plugins.core.web_component import parse_initial_value++ t = ui.text(value="secret123", kind="password")++ # Python-side values are the real password+ assert t.value == "secret123"+ assert t._initial_value == "secret123"++ # Frontend-facing values are sanitized+ assert "secret123" not in t.text+ assert t._initial_value_frontend == ""+ assert parse_initial_value(t._inner_text) == ""++ # password-has-value arg is set+ assert t._component_args.get("password-has-value") is True++ # Update works normally+ t._update("new_password")+ assert t.value == "new_password"++ # Password without value: no masking needed+ t = ui.text(kind="password")+ assert t.value == ""+ assert t._component_args.get("password-has-value") is None++ # Non-password text: value appears in HTML normally+ t = ui.text(value="hello")+ assert "hello" in t.text+++def test_text_password_masking_clone() -> None:+ from marimo._plugins.core.web_component import parse_initial_value++ t = ui.text(value="secret123", kind="password")+ clone = t._clone()++ # Clone preserves the real password in Python+ assert clone.value == "secret123"+ assert clone._initial_value == "secret123"++ # Clone's HTML is also sanitized+ assert "secret123" not in clone.text+ assert clone._initial_value_frontend == ""+ assert parse_initial_value(clone._inner_text) == ""+++def test_text_password_masking_form_submit() -> None:+ # Form wraps a clone — password is preserved+ t = ui.text(value="secret123", kind="password")+ f = t.form()+ assert f.element.value == "secret123"++ # Submit without editing: "" is ignored while masked+ f._update("")+ assert f.value == "secret123"++ # Submit after user types: new value is used+ f2 = ui.text(value="secret123", kind="password").form()+ f2._update("new_password")+ assert f2.value == "new_password"++ # After unmasking, intentionally clearing to "" is accepted+ t2 = ui.text(value="secret123", kind="password")+ t2._update("a") # unmask+ t2._update("") # intentional clear+ assert t2.value == ""++def test_checkbox_init() -> None:assert not ui.checkbox().valueassert ui.checkbox(value=True).value