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
add auth token endpoint and --with-token flow for pair programming (#9003)
Myles Scolnick3682529d8dc0
diff --git a/frontend/src/components/editor/actions/pair-with-agent-modal.tsx b/frontend/src/components/editor/actions/pair-with-agent-modal.tsxindex 51cf4af6b9..a97eac71e8 100644--- a/frontend/src/components/editor/actions/pair-with-agent-modal.tsx+++ b/frontend/src/components/editor/actions/pair-with-agent-modal.tsx@@ -1,8 +1,7 @@/* Copyright 2026 Marimo. All rights reserved. */-import { useAtomValue } from "jotai";import { CheckIcon, CopyIcon } from "lucide-react";-import React, { useState } from "react";+import React, { useEffect, useState } from "react";import { Button } from "@/components/ui/button";import {DialogContent,@@ -12,25 +11,25 @@ import {DialogTitle,} from "@/components/ui/dialog";import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";-import { runtimeConfigAtom } from "@/core/runtime/config";import { copyToClipboard } from "@/utils/copy";import { Events } from "@/utils/events";import { Tooltip } from "@/components/ui/tooltip";-import type { RuntimeConfig } from "@/core/runtime/types";+import { assertNever } from "@/utils/assertNever";+import { asRemoteURL, useRuntimeManager } from "@/core/runtime/config";type AgentTab = "claude" | "codex" | "opencode";-function buildRemoteUrl(config: RuntimeConfig) {- const url = new URL(config.url);- if (config.authToken) {- url.searchParams.set("auth", config.authToken);- }- return url.toString();+function getMarimoCommand(): string {+ return import.meta.env.DEV ? "uv run marimo" : "uvx marimo@latest";}-function getPromptCommand(agent: AgentTab, remoteUrl: string): string {- const command = import.meta.env.DEV ? "uv run marimo" : "uvx marimo@latest";- const base = `${command} pair prompt --url '${remoteUrl}'`;+function getPromptCommand(+ agent: AgentTab,+ url: string,+ withToken: boolean,+): string {+ const tokenFlag = withToken ? " --with-token" : "";+ const base = `${getMarimoCommand()} pair prompt --url '${url}'${tokenFlag}`;switch (agent) {case "claude":return `claude "$(${base} --claude)"`;@@ -38,18 +37,42 @@ function getPromptCommand(agent: AgentTab, remoteUrl: string): string {return `codex "$(${base} --codex)"`;case "opencode":return `opencode "$(${base} --opencode)"`;+ default:+ assertNever(agent);+ }+}++function maskToken(token: string): string {+ if (token.length <= 4) {+ return "****";}+ return `${"*".repeat(Math.min(token.length - 4, 8))}${token.slice(-4)}`;}const SKILL_INSTALL = "npx skills add marimo-team/marimo-pair";+function useAuthToken(): string | null {+ const [token, setToken] = useState<string | null>(null);+ useEffect(() => {+ fetch(asRemoteURL("/auth/token").href, { credentials: "include" })+ .then((res) =>+ res.ok ? (res.json() as Promise<{ token: string | null }>) : null,+ )+ .then((data) => setToken(data?.token ?? null))+ .catch(() => setToken(null));+ }, []);+ return token;+}+export const PairWithAgentModal: React.FC<{onClose: () => void;}> = ({ onClose }) => {const [activeTab, setActiveTab] = useState<AgentTab>("claude");- const runtimeConfig = useAtomValue(runtimeConfigAtom);- const remoteUrl = buildRemoteUrl(runtimeConfig);- const promptCommand = getPromptCommand(activeTab, remoteUrl);+ const runtimeManager = useRuntimeManager();+ const authToken = useAuthToken();+ const hasToken = Boolean(authToken);+ const remoteUrl = runtimeManager.httpURL.toString();+ const promptCommand = getPromptCommand(activeTab, remoteUrl, hasToken);return (<DialogContent className="sm:max-w-lg">@@ -104,6 +127,15 @@ export const PairWithAgentModal: React.FC<{</TabsContent></Tabs></div>++ {hasToken && authToken && (+ <div className="flex flex-col gap-2">+ <span className="text-sm font-medium">+ 3. Paste when prompted for token+ </span>+ <CommandBlock command={authToken} display={maskToken(authToken)} />+ </div>+ )}</div><DialogFooter>@@ -115,7 +147,10 @@ export const PairWithAgentModal: React.FC<{);};-const CommandBlock: React.FC<{ command: string }> = ({ command }) => {+const CommandBlock: React.FC<{ command: string; display?: string }> = ({+ command,+ display,+}) => {const [copied, setCopied] = useState(false);const copy = Events.stopPropagation(async (e) => {@@ -127,7 +162,9 @@ const CommandBlock: React.FC<{ command: string }> = ({ command }) => {return (<div className="flex items-center gap-2 rounded-md bg-muted px-3 py-2 font-mono text-xs">- <code className="flex-1 select-all break-words">{command}</code>+ <code className="flex-1 select-all break-words">+ {display ?? command}+ </code><Tooltip content="Copied!" open={copied}><Button onClick={copy} size="xs" variant="ghost">{copied ? (diff --git a/marimo/_cli/pair/commands.py b/marimo/_cli/pair/commands.pyindex 84b06c64c0..3f7634dbe2 100644--- a/marimo/_cli/pair/commands.py+++ b/marimo/_cli/pair/commands.py@@ -1,7 +1,8 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations-import sys+import hashlib+import osfrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -13,6 +14,18 @@ SKILL_NAME = "marimo-pair"SKILL_FILE = "SKILL.md"+_cached_token_dir: Path | None = None+++def _token_dir() -> Path:+ import tempfile++ global _cached_token_dir # noqa: PLW0603+ if _cached_token_dir is None:+ _cached_token_dir = Path(tempfile.mkdtemp(prefix="marimo-pair-"))+ return _cached_token_dir++@dataclass(frozen=True)class AgentConfig:name: str@@ -93,16 +106,32 @@ def pair() -> None:default=False,help="Validate that the marimo-pair opencode skill is installed.",)-def prompt(url: str, claude: bool, codex: bool, opencode: bool) -> None:+ "--with-token",+ is_flag=True,+ default=False,+ help="Prompt for an auth token and store it in a temp file.",+)+def prompt(+ url: str,+ claude: bool,+ codex: bool,+ opencode: bool,+ with_token: bool,+) -> None:"""Generate a prompt for pair programming.Example usage:- claude $(marimo pair prompt --url 'https://localhost:8000?auth=...' --claude)- codex $(marimo pair prompt --url 'https://localhost:8000?auth=...' --codex)- opencode $(marimo pair prompt --url 'https://localhost:8000?auth=...' --opencode)+ claude "$(uvx marimo@latest pair prompt --url 'https://localhost:8000' --claude)"+ codex "$(uvx marimo@latest pair prompt --url 'https://localhost:8000' --codex)"+ opencode "$(uvx marimo@latest pair prompt --url 'https://localhost:8000' --opencode)"++ # With an auth token+ claude "$(uvx marimo@latest pair prompt --url 'https://localhost:8000' --claude --with-token)""""+ # Validate that the selected agents have the required skillsselected_agents = {"claude": claude,"codex": codex,@@ -113,8 +142,8 @@ def prompt(url: str, claude: bool, codex: bool, opencode: bool) -> None:continueif not agent.has_skill():click.echo(- f"The marimo-pair skill for {agent.name} is not installed.\n\n"- "Let the user know they need to install it with:\n\n"+ f"The marimo-pair skill for {agent.name} could not be found.\n\n"+ "Please install it with:\n\n"" npx skills add marimo-team/marimo-pair\n\n""or\n\n"" uvx deno -A npm:skills add marimo-team/marimo-pair\n\n"@@ -122,14 +151,38 @@ def prompt(url: str, claude: bool, codex: bool, opencode: bool) -> None:"https://github.com/marimo-team/marimo-pair",err=True,)- sys.exit(1)+ # Prompt for token and write it to a temp file if --with-token is set+ token_hint = ""+ if with_token:+ token_dir = _token_dir()+ url_hash = hashlib.sha256(url.encode()).hexdigest()[:6]+ token_file = token_dir / f"{url_hash}-token.txt"+ token = click.prompt("Auth token", hide_input=True, err=True)+ token_dir.mkdir(parents=True, exist_ok=True)+ # Open the token file for writing, creating it with restrictive+ # permissions if needed and truncating it if it already exists.+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC+ fd = os.open(token_file, flags, 0o600)+ try:+ os.write(fd, token.encode())+ finally:+ os.close(fd)++ token_hint = (+ f"\n\nAn auth token is stored at {token_file}. "+ f"Pass it via `execute-code.sh --url '{url}' "+ f"--token \"$(cat '{token_file}')\"`."+ )++ # Output the prompt to the wrapper agent CLIclick.echo("Use the /marimo-pair skill to pair-program on a running ""marimo notebook.\n\n"f"Connect to the notebook at: {url}\n\n"f"Use `execute-code.sh --url {url}` from the marimo-pair "- "skill to execute code in the notebook. \n\n"+ "skill to execute code in the notebook."+ f"{token_hint}\n\n""Once you are connected, send a fun toast to the user inside marimo letting them know you're ready to pair.")diff --git a/marimo/_server/api/auth.py b/marimo/_server/api/auth.pyindex 0821ece2fc..748fc47e38 100644--- a/marimo/_server/api/auth.py+++ b/marimo/_server/api/auth.py@@ -2,6 +2,7 @@from __future__ import annotationsimport base64+import hmacimport secretsimport typingfrom typing import TYPE_CHECKING, Any, Optional@@ -41,13 +42,15 @@ def validate_auth(cookie_session = CookieSession(conn.session)# Validate the cookie- if cookie_session.get_access_token() == auth_token:+ if hmac.compare_digest(cookie_session.get_access_token(), auth_token):return True # Success# Check for access_tokenif TOKEN_QUERY_PARAM in conn.query_params:# Validate the access_token- if conn.query_params[TOKEN_QUERY_PARAM] == auth_token:+ if hmac.compare_digest(+ conn.query_params[TOKEN_QUERY_PARAM], auth_token+ ):LOGGER.debug("Validated access_token from query param")# Set the cookiecookie_session.set_access_token(auth_token)@@ -57,7 +60,7 @@ def validate_auth(if form_dict is not None:# Validate the access_tokenpassword = form_dict.get("password")- if password == auth_token:+ if password and hmac.compare_digest(password, auth_token):LOGGER.debug("Validated access_token from form data")# Set the cookiecookie_session.set_access_token(auth_token)@@ -66,37 +69,50 @@ def validate_auth(LOGGER.warning("Invalid password from form data.")return False- # Check for basic auth+ # Check for Authorization header (Bearer or Basic)auth = conn.headers.get("Authorization")if auth is not None:- username, password = _parse_basic_auth_header(auth)- if username and password == auth_token:- LOGGER.debug("Validated basic auth from header")- # Set the cookie+ scheme, _, credentials = auth.partition(" ")+ scheme_lower = scheme.lower()++ if scheme_lower == "bearer" and hmac.compare_digest(+ credentials, auth_token+ ):+ LOGGER.debug("Validated bearer token from header")cookie_session.set_access_token(auth_token)- cookie_session.set_username(username)return True # Success+ if scheme_lower == "basic":+ username, password = _parse_basic_auth_credentials(credentials)+ if (+ username+ and password+ and hmac.compare_digest(password, auth_token)+ ):+ LOGGER.debug("Validated basic auth from header")+ cookie_session.set_access_token(auth_token)+ cookie_session.set_username(username)+ return True # Success+LOGGER.debug("Invalid auth")return False-def _parse_basic_auth_header(- header: str,+def _parse_basic_auth_credentials(+ credentials: str,) -> tuple[Optional[str], Optional[str]]:- scheme, _, credentials = header.partition(" ")-- if scheme.lower() != "basic":- LOGGER.debug("Invalid auth scheme: %s", scheme)+ try:+ decoded = base64.b64decode(credentials).decode("utf-8")+ except Exception:+ LOGGER.debug("Invalid base64 in basic auth credentials")return None, None- decoded = base64.b64decode(credentials).decode("utf-8")username, _, password = decoded.partition(":")if not password:return None, None- LOGGER.debug("Validated basic auth for user: %s", username)+ LOGGER.debug("Parsed basic auth credentials for user: %s", username)return username, passworddiff --git a/marimo/_server/api/endpoints/login.py b/marimo/_server/api/endpoints/login.pyindex 381706dbdf..0e1d0ae16c 100644--- a/marimo/_server/api/endpoints/login.py+++ b/marimo/_server/api/endpoints/login.py@@ -4,8 +4,10 @@ from __future__ import annotationsfrom typing import TYPE_CHECKINGfrom urllib.parse import parse_qsl, urlparse+from starlette.authentication import requiresfrom starlette.responses import (HTMLResponse,+ JSONResponse,RedirectResponse,Response,)@@ -152,6 +154,33 @@ async def login_page(request: Request) -> HTMLResponse:)[email protected]("/token")+@requires("edit")+async def auth_token(request: Request) -> JSONResponse:+ """+ tags: [auth]+ summary: Get the auth token for the current session+ responses:+ 200:+ description: The auth token (null if auth is disabled)+ content:+ application/json:+ schema:+ type: object+ properties:+ token:+ type: string+ nullable: true+ """+ state = AppState(request)+ no_cache = {"Cache-Control": "no-store"}+ if not state.enable_auth:+ return JSONResponse({"token": None}, headers=no_cache)+ return JSONResponse(+ {"token": str(state.session_manager.auth_token)}, headers=no_cache+ )++def _with_trailing_slash(url: str) -> str:if not url.endswith("/"):return url + "/"diff --git a/tests/_cli/test_cli_pair.py b/tests/_cli/test_cli_pair.pyindex 1e55f796d8..6ab3aa3f42 100644--- a/tests/_cli/test_cli_pair.py+++ b/tests/_cli/test_cli_pair.py@@ -1,6 +1,8 @@# Copyright 2026 Marimo. All rights reserved.from __future__ import annotations+import hashlib+from typing import TYPE_CHECKINGfrom unittest.mock import patchfrom click.testing import CliRunner@@ -12,6 +14,9 @@ _runner = CliRunner()TEST_URL = "https://localhost:8000?auth=tok123"+if TYPE_CHECKING:+ from pathlib import Path+class TestPairGroup:def test_pair_help(self) -> None:@@ -62,3 +67,122 @@ class TestPairPrompt:)assert result.exit_code == 0, flagassert TEST_URL in result.output, flag+++class TestPairPromptWithToken:+ def test_with_token_writes_file_and_outputs_prompt(+ self, tmp_path: Path+ ) -> None:+ with patch(+ "marimo._cli.pair.commands._token_dir", return_value=tmp_path+ ):+ result = _runner.invoke(+ cli_main,+ ["pair", "prompt", "--url", TEST_URL, "--with-token"],+ input="my-secret-token\n",+ )+ assert result.exit_code == 0+ assert TEST_URL in result.output+ assert "execute-code.sh" in result.output+ assert "token" in result.output.lower()+ assert "cat" in result.output++ url_hash = hashlib.sha256(TEST_URL.encode()).hexdigest()[:6]+ token_file = tmp_path / f"{url_hash}-token.txt"+ assert token_file.exists()+ assert token_file.read_text() == "my-secret-token"+ assert oct(token_file.stat().st_mode & 0o777) == "0o600"++ def test_with_token_still_requires_url(self) -> None:+ result = _runner.invoke(+ cli_main,+ ["pair", "prompt", "--with-token"],+ input="tok\n",+ )+ assert result.exit_code != 0++ def test_with_token_and_agent_flag(self, tmp_path: Path) -> None:+ with (+ patch.object(AgentConfig, "has_skill", return_value=True),+ patch(+ "marimo._cli.pair.commands._token_dir",+ return_value=tmp_path,+ ),+ ):+ result = _runner.invoke(+ cli_main,+ [+ "pair",+ "prompt",+ "--url",+ TEST_URL,+ "--claude",+ "--with-token",+ ],+ input="secret\n",+ )+ assert result.exit_code == 0+ assert TEST_URL in result.output+ assert "token" in result.output.lower()++ def test_with_token_and_skill_missing_fails(self) -> None:+ with patch.object(AgentConfig, "has_skill", return_value=False):+ result = _runner.invoke(+ cli_main,+ [+ "pair",+ "prompt",+ "--url",+ TEST_URL,+ "--claude",+ "--with-token",+ ],+ input="secret\n",+ )+ assert result.exit_code != 0+ assert "not installed" in result.output++ def test_without_token_no_token_hint(self) -> None:+ result = _runner.invoke(+ cli_main, ["pair", "prompt", "--url", TEST_URL]+ )+ assert result.exit_code == 0+ assert "cat" not in result.output+++class TestAgentConfig:+ def test_has_skill_true(self, tmp_path: Path) -> None:+ skill_dir = tmp_path / "skills"+ (skill_dir / "marimo-pair").mkdir(parents=True)+ (skill_dir / "marimo-pair" / "SKILL.md").write_text("test")++ agent = AgentConfig(name="test", skill_dirs=[skill_dir])+ assert agent.has_skill() is True++ def test_has_skill_false(self, tmp_path: Path) -> None:+ agent = AgentConfig(name="test", skill_dirs=[tmp_path / "nonexistent"])+ assert agent.has_skill() is False++ def test_has_skill_empty_dirs(self) -> None:+ agent = AgentConfig(name="test", skill_dirs=[])+ assert agent.has_skill() is False++ def test_has_skill_multiple_dirs_first_match(self, tmp_path: Path) -> None:+ dir1 = tmp_path / "a" / "skills"+ dir2 = tmp_path / "b" / "skills"+ (dir1 / "marimo-pair").mkdir(parents=True)+ (dir1 / "marimo-pair" / "SKILL.md").write_text("test")++ agent = AgentConfig(name="test", skill_dirs=[dir1, dir2])+ assert agent.has_skill() is True++ def test_has_skill_multiple_dirs_second_match(+ self, tmp_path: Path+ ) -> None:+ dir1 = tmp_path / "a" / "skills"+ dir2 = tmp_path / "b" / "skills"+ (dir2 / "marimo-pair").mkdir(parents=True)+ (dir2 / "marimo-pair" / "SKILL.md").write_text("test")++ agent = AgentConfig(name="test", skill_dirs=[dir1, dir2])+ assert agent.has_skill() is Truediff --git a/tests/_server/api/endpoints/test_login.py b/tests/_server/api/endpoints/test_login.pyindex ba24f437d6..7aeafdf9ee 100644--- a/tests/_server/api/endpoints/test_login.py+++ b/tests/_server/api/endpoints/test_login.py@@ -196,3 +196,51 @@ def test_login_submit_invalid_password_with_base_url():assert response.status_code == 200assert "Invalid password" in response.textassert 'action="/app/auth/login"' in response.text+++def test_auth_token_returns_token_when_authenticated(client: TestClient):+ """Authenticated user gets the auth token."""+ # First authenticate via login+ client.post("/login", data={"password": str(AUTH_TOKEN)})+ response = client.get("/token")+ assert response.status_code == 200+ data = response.json()+ assert data["token"] == str(AUTH_TOKEN)+ assert response.headers["Cache-Control"] == "no-store"+++def test_auth_token_unauthenticated_returns_403(client: TestClient):+ """Unauthenticated request to /token is rejected."""+ response = client.get("/token")+ assert response.status_code == 403+++def test_auth_token_returns_null_when_auth_disabled():+ """When auth is disabled, /token returns null."""+ app = create_app()+ app.state.enable_auth = False+ # Auth middleware still present but we authenticate first+ test_client = TestClient(app, follow_redirects=False)+ test_client.post("/login", data={"password": str(AUTH_TOKEN)})+ response = test_client.get("/token")+ assert response.status_code == 200+ assert response.json()["token"] is None+++def test_bearer_auth_valid_token(client: TestClient):+ """Bearer token auth grants access."""+ response = client.get(+ "/token",+ headers={"Authorization": f"Bearer {AUTH_TOKEN}"},+ )+ assert response.status_code == 200+ assert response.json()["token"] == str(AUTH_TOKEN)+++def test_bearer_auth_invalid_token(client: TestClient):+ """Bearer token with wrong value is rejected."""+ response = client.get(+ "/token",+ headers={"Authorization": "Bearer wrong-token"},+ )+ assert response.status_code == 403