Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.
feature/pipelex-login (#736)
Thomas Hebrardc90cc608df52
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0a0adb843..e031e8fc8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,12 @@# Changelog+## [Unreleased]++### Added++- **`pipelex login`** — new CLI command for browser-based Pipelex Gateway authentication. Starts a local HTTP server, opens the browser for OAuth login (GitHub or Google), and saves the Gateway API key to `~/.pipelex/.env`. The key never appears in terminal output. Includes a 120-second timeout with helpful fallback instructions.+- Added `app_cli_auth` URL to `URLs` class pointing to `https://app.pipelex.com/auth/cli`.+## [v0.19.0] - 2026-03-02### Addeddiff --git a/pipelex/cli/_cli.py b/pipelex/cli/_cli.pyindex da04261ba..de73d1247 100644--- a/pipelex/cli/_cli.py+++ b/pipelex/cli/_cli.py@@ -11,6 +11,7 @@ from pipelex.cli.commands.doctor_cmd import doctor_cmdfrom pipelex.cli.commands.graph_cmd import graph_appfrom pipelex.cli.commands.init.command import init_cmdfrom pipelex.cli.commands.init.ui.types import InitFocus+from pipelex.cli.commands.login.command import login_cmdfrom pipelex.cli.commands.run.app import run_appfrom pipelex.cli.commands.show_cmd import show_appfrom pipelex.cli.commands.validate.app import validate_app@@ -26,7 +27,7 @@ class PipelexCLI(TyperGroup):@overridedef list_commands(self, ctx: Context) -> list[str]:# List the commands in the proper order because natural ordering doesn't work between Typer groups and commands- return ["init", "doctor", "build", "validate", "run", "graph", "show", "which"]+ return ["login", "init", "doctor", "build", "validate", "run", "graph", "show", "which"]@overridedef get_command(self, ctx: Context, cmd_name: str) -> Command | None:@@ -115,13 +116,19 @@ def app_callback(""")# Skip checks if no command is being run (e.g., just --help) or if running init/doctor command- if ctx.invoked_subcommand is None or ctx.invoked_subcommand in {"init", "doctor"}:+ if ctx.invoked_subcommand is None or ctx.invoked_subcommand in {"login", "init", "doctor"}:return# Check system readiness (dependencies and venv for dev installs)check_readiness()[email protected](name="login", help="Log in to Pipelex Gateway via the browser and save your API key")+def login_command() -> None:+ """Open the browser to authenticate and save your Pipelex Gateway API key."""+ login_cmd()++@app.command(name="init", help="Initialize Pipelex configuration, backends, credentials, routing, and telemetry")def init_command(focus: Annotated[diff --git a/pipelex/cli/commands/login/__init__.py b/pipelex/cli/commands/login/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/pipelex/cli/commands/login/command.py b/pipelex/cli/commands/login/command.pynew file mode 100644index 000000000..7c5d7481b--- /dev/null+++ b/pipelex/cli/commands/login/command.py@@ -0,0 +1,120 @@+"""Browser-based CLI authentication for Pipelex Gateway."""++from __future__ import annotations++import threading+import webbrowser+from functools import partial+from http.server import BaseHTTPRequestHandler, HTTPServer+from urllib.parse import parse_qs, urlparse++from typing_extensions import override++from pipelex.cli.commands.init.credentials import get_global_env_path, read_env_file, write_env_file+from pipelex.hub import get_console+from pipelex.urls import URLs++LOGIN_TIMEOUT_SECONDS = 120+PIPELEX_GATEWAY_API_KEY_VAR = "PIPELEX_GATEWAY_API_KEY"+++class CallbackHandler(BaseHTTPRequestHandler):+ """HTTP handler that receives the API key callback from the browser."""++ def __init__(self, result: dict[str, str | None], *args: object, **kwargs: object) -> None:+ self._result = result+ super().__init__(*args, **kwargs) # type: ignore[arg-type]++ def do_GET(self) -> None:+ """Handle GET /callback?api_key=xxx."""+ parsed = urlparse(self.path)+ params = parse_qs(parsed.query)+ api_key_list = params.get("api_key", [])++ if parsed.path == "/callback" and api_key_list:+ self._result["api_key"] = api_key_list[0]+ self._send_success_page()+ else:+ self._send_error_page()++ def _send_success_page(self) -> None:+ self.send_response(200)+ self.send_header("Content-Type", "text/html")+ self.end_headers()+ html = (+ "<html><body style='font-family:system-ui;text-align:center;padding:60px'>"+ "<h1>Logged in successfully!</h1>"+ "<p>You can close this tab and return to your terminal.</p>"+ "</body></html>"+ )+ self.wfile.write(html.encode())++ def _send_error_page(self) -> None:+ self.send_response(400)+ self.send_header("Content-Type", "text/html")+ self.end_headers()+ html = (+ "<html><body style='font-family:system-ui;text-align:center;padding:60px'>"+ "<h1>Authentication failed</h1>"+ "<p>Missing API key parameter. Please try again.</p>"+ "</body></html>"+ )+ self.wfile.write(html.encode())++ @override+ def log_message(self, format: str, *args: object) -> None:+ """Suppress default HTTP server logging."""+++def login_cmd() -> None:+ """Open the browser for Pipelex Gateway login and save the API key."""+ console = get_console()++ result: dict[str, str | None] = {"api_key": None}+ handler_cls = partial(CallbackHandler, result)++ server = HTTPServer(("127.0.0.1", 0), handler_cls) # type: ignore[arg-type]+ port = server.server_address[1]++ auth_url = f"{URLs.app_cli_auth}?callback_port={port}"++ console.print("\n[bold]Opening browser for login...[/bold]")+ console.print(f"[dim]If it doesn't open, visit: {auth_url}[/dim]\n")++ webbrowser.open(auth_url)++ server.timeout = LOGIN_TIMEOUT_SECONDS+ server_thread = threading.Thread(target=serve_until_callback, args=(server, result), daemon=True)+ server_thread.start()+ server_thread.join(timeout=LOGIN_TIMEOUT_SECONDS)++ server.server_close()++ if result["api_key"]:+ save_api_key(result["api_key"])+ console.print("[bold green]Logged in successfully![/bold green]")+ console.print(f"[dim]API key saved to {get_global_env_path()}[/dim]\n")+ else:+ console.print("[bold red]Login timed out.[/bold red]")+ console.print(f"[dim]No response received within {LOGIN_TIMEOUT_SECONDS}s.[/dim]")+ console.print("[dim]You can try again with: pipelex login[/dim]")+ console.print(f"[dim]Or visit {URLs.app} to generate your API key manually.[/dim]\n")+ raise SystemExit(1)+++def serve_until_callback(server: HTTPServer, result: dict[str, str | None]) -> None:+ """Handle requests until we get the API key or timeout."""+ try:+ while result["api_key"] is None:+ server.handle_request()+ except OSError:+ # Socket closed by main thread after timeout — expected during shutdown.+ pass+++def save_api_key(api_key: str) -> None:+ """Write the API key to ~/.pipelex/.env."""+ env_path = get_global_env_path()+ entries = read_env_file(env_path)+ entries[PIPELEX_GATEWAY_API_KEY_VAR] = api_key+ write_env_file(env_path, entries)diff --git a/pipelex/urls.py b/pipelex/urls.pyindex e2a2e0257..e00b280ce 100644--- a/pipelex/urls.py+++ b/pipelex/urls.py@@ -13,6 +13,7 @@ class URLs:pipe_func_docs = "https://docs.pipelex.com/latest/home/6-build-reliable-ai-workflows/pipes/pipe-operators/PipeFunc/"backend_provider_docs = "https://docs.pipelex.com/latest/home/5-setup/configure-ai-providers/"native_concepts_docs = "https://docs.pipelex.com/latest/home/6-build-reliable-ai-workflows/concepts/native-concepts/"+ app_cli_auth = "https://app.pipelex.com/auth/cli"jpg_example_1 = "https://pipelex-pytest-assets.s3.eu-west-3.amazonaws.com/jpg_example_1.jpg"jpg_example_2 = "https://pipelex-pytest-assets.s3.eu-west-3.amazonaws.com/jpg_example_2.jpg"diff --git a/tests/unit/pipelex/cli/commands/login/test_login_command.py b/tests/unit/pipelex/cli/commands/login/test_login_command.pynew file mode 100644index 000000000..a41d86d57--- /dev/null+++ b/tests/unit/pipelex/cli/commands/login/test_login_command.py@@ -0,0 +1,152 @@+"""Tests for the pipelex login command."""++from __future__ import annotations++import http.client+import threading+from functools import partial+from http.server import HTTPServer+from io import StringIO+from typing import TYPE_CHECKING++from rich.console import Console++from pipelex.cli.commands.init.credentials import read_env_file, write_env_file+from pipelex.cli.commands.login.command import (+ PIPELEX_GATEWAY_API_KEY_VAR,+ CallbackHandler,+ login_cmd,+ save_api_key,+)++if TYPE_CHECKING:+ from pathlib import Path++ from pytest_mock import MockerFixture+++class TestLoginCommand:+ def test_callback_handler_extracts_api_key(self) -> None:+ """The callback handler extracts the api_key param and stores it in result."""+ result: dict[str, str | None] = {"api_key": None}+ handler_cls = partial(CallbackHandler, result)+ server = HTTPServer(("127.0.0.1", 0), handler_cls) # type: ignore[arg-type]+ port = server.server_address[1]++ server_thread = threading.Thread(target=server.handle_request, daemon=True)+ server_thread.start()++ conn = http.client.HTTPConnection("127.0.0.1", port)+ conn.request("GET", "/callback?api_key=test-key-12345")+ response = conn.getresponse()+ conn.close()+ server_thread.join(timeout=5)+ server.server_close()++ assert response.status == 200+ assert result["api_key"] == "test-key-12345"++ def test_callback_handler_returns_400_without_key(self) -> None:+ """The callback handler returns 400 when api_key param is missing."""+ result: dict[str, str | None] = {"api_key": None}+ handler_cls = partial(CallbackHandler, result)+ server = HTTPServer(("127.0.0.1", 0), handler_cls) # type: ignore[arg-type]+ port = server.server_address[1]++ server_thread = threading.Thread(target=server.handle_request, daemon=True)+ server_thread.start()++ conn = http.client.HTTPConnection("127.0.0.1", port)+ conn.request("GET", "/callback")+ response = conn.getresponse()+ conn.close()+ server_thread.join(timeout=5)+ server.server_close()++ assert response.status == 400+ assert result["api_key"] is None++ def test_callback_handler_returns_400_for_wrong_path(self) -> None:+ """The callback handler returns 400 for paths other than /callback."""+ result: dict[str, str | None] = {"api_key": None}+ handler_cls = partial(CallbackHandler, result)+ server = HTTPServer(("127.0.0.1", 0), handler_cls) # type: ignore[arg-type]+ port = server.server_address[1]++ server_thread = threading.Thread(target=server.handle_request, daemon=True)+ server_thread.start()++ conn = http.client.HTTPConnection("127.0.0.1", port)+ conn.request("GET", "/other?api_key=test-key")+ response = conn.getresponse()+ conn.close()+ server_thread.join(timeout=5)+ server.server_close()++ assert response.status == 400+ assert result["api_key"] is None++ def test_save_api_key_creates_env_file(self, tmp_path: Path, mocker: MockerFixture) -> None:+ """save_api_key writes the key to ~/.pipelex/.env."""+ env_path = tmp_path / ".env"+ mocker.patch(+ "pipelex.cli.commands.login.command.get_global_env_path",+ return_value=env_path,+ )+ save_api_key("pk_live_test123")++ entries = read_env_file(env_path)+ assert entries[PIPELEX_GATEWAY_API_KEY_VAR] == "pk_live_test123"++ def test_save_api_key_preserves_existing_entries(self, tmp_path: Path, mocker: MockerFixture) -> None:+ """save_api_key preserves existing .env entries when adding the API key."""+ env_path = tmp_path / ".env"+ write_env_file(env_path, {"EXISTING_KEY": "existing_value"})++ mocker.patch(+ "pipelex.cli.commands.login.command.get_global_env_path",+ return_value=env_path,+ )+ save_api_key("pk_live_test456")++ entries = read_env_file(env_path)+ assert entries["EXISTING_KEY"] == "existing_value"+ assert entries[PIPELEX_GATEWAY_API_KEY_VAR] == "pk_live_test456"++ def test_save_api_key_updates_existing_key(self, tmp_path: Path, mocker: MockerFixture) -> None:+ """save_api_key overwrites an existing PIPELEX_GATEWAY_API_KEY."""+ env_path = tmp_path / ".env"+ write_env_file(env_path, {PIPELEX_GATEWAY_API_KEY_VAR: "old_key"})++ mocker.patch(+ "pipelex.cli.commands.login.command.get_global_env_path",+ return_value=env_path,+ )+ save_api_key("new_key")++ entries = read_env_file(env_path)+ assert entries[PIPELEX_GATEWAY_API_KEY_VAR] == "new_key"++ def test_login_cmd_stdout_never_contains_api_key(self, tmp_path: Path, mocker: MockerFixture) -> None:+ """login_cmd never prints the API key to stdout."""+ env_path = tmp_path / ".env"+ mocker.patch(+ "pipelex.cli.commands.login.command.get_global_env_path",+ return_value=env_path,+ )++ output = StringIO()+ mock_console = Console(file=output)+ mocker.patch("pipelex.cli.commands.login.command.get_console", return_value=mock_console)+ mocker.patch("pipelex.cli.commands.login.command.webbrowser.open")++ # Mock serve_until_callback to immediately set the api_key in login_cmd's own result dict+ def fake_serve(_server: object, result: dict[str, str | None]) -> None:+ result["api_key"] = "secret_key_12345"++ mocker.patch("pipelex.cli.commands.login.command.serve_until_callback", side_effect=fake_serve)++ login_cmd()++ printed = output.getvalue()+ assert "secret_key_12345" not in printed