From 110b138301a4920e0a25d6614644624602943cc3 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:08:16 +0100 Subject: [PATCH 01/10] Support stable development MCP configuration (#637) --- docs/AUTOMATION.md | 19 ++++++- docs/CHANGELOG.md | 1 + docs/DEVELOPING_WITH_AGENTS.md | 4 +- docs/PROJECT_STATUS.md | 2 + .../ADR-026-configuration-mcp-persistante.md | 23 ++++++++ docs/adr/README.md | 5 +- include/webfront/automation/Enable.hpp | 6 ++- include/webfront/automation/McpHttp.hpp | 42 +++++++++------ js/developer/environment/bundles.json | 2 +- js/developer/starters/agent-guide.md | 2 + test/cmake/CheckAgentGuide.cmake | 2 +- test/tools/AutomationClient.py | 35 ++++++++++++- test/unit/AutomationMcpHttpTests.cpp | 52 +++++++++++++++++++ test/web/AutomationHost.cpp | 8 +++ test/web/CMakeLists.txt | 2 + 15 files changed, 181 insertions(+), 24 deletions(-) create mode 100644 docs/adr/ADR-026-configuration-mcp-persistante.md diff --git a/docs/AUTOMATION.md b/docs/AUTOMATION.md index 2b8574e7..eef2c907 100644 --- a/docs/AUTOMATION.md +++ b/docs/AUTOMATION.md @@ -52,6 +52,8 @@ change them. | `grants` | none | The granted operations: `check`, `build`, `test`, `preview`, `inspect`, `interact` (click/fill), `call`, and the setup grants `init`, `create`, `install`, `restore`, `embed`. None leaves only session discovery. | | `callbacks` | none | The application callbacks `call` may invoke, by exact name (see below). | | `mcpPort` | 0 | The port of the listener; 0 lets the OS choose. A chosen port is never replaced: when it is taken the activation throws a `std::system_error` that names the address, the port and the cause. | +| `mcpToken` | absent | An application-supplied Bearer token, retained across launches if the application supplies the same value. Absent selects a fresh random token per session. Use a long random secret outside the project. | +| `disableMcpAuthentication` | false | Explicitly allow local clients without a Bearer token. Cannot be combined with `mcpToken`. | | `directory` | a new directory named after the session in the discovery directory | A new private directory outside the project for `mcp.json`. | | `discovery` | the per-user sessions directory | Where the record goes (tests use their own). | | `timeout` | 120 s | The native deadline of one operation. | @@ -59,6 +61,20 @@ change them. | `closeGrace` | 5 s | How long a revoked window may take to close before `onUnresponsive`. | | `onUnresponsive` | ends the process with status 72 | What to do with a window that did not close. | +For a client configured once, set `mcpPort` to a fixed nonzero port and supply the same `mcpToken` on every launch, for example from a private environment variable read by the application. Copy the URL and Authorization header from the first `mcp.json` into the client's **user** configuration, outside the project. Start the application before connecting; retry after starting it if the connection is refused. Rotate the token by changing the application-supplied value and updating the client. A second instance can use the default options; a second listener on the chosen port fails explicitly. + +```cpp +const char* token = std::getenv("MY_APP_MCP_TOKEN"); +if (!token || !*token) + throw std::runtime_error("Set MY_APP_MCP_TOKEN to a private random token"); +auto automation = webfront::automation::enableAutomation( + app, {.grants = {"check", "build"}, .mcpPort = 19002, .mcpToken = std::string{token}}); +``` + +The application includes ``, `` and `` for this example. A configured token must be 1–1024 visible ASCII characters without spaces. To opt in to an unauthenticated listener instead, use `.disableMcpAuthentication = true` and omit `mcpToken`; its client configuration has no Authorization header. + +These options are for trusted development environments. A different local user can occupy the fixed port while the application is stopped and receive a durable Bearer sent by the client, then reuse it when the application starts. Without authentication, any local process that reaches the listener can exercise its grants. A fake server can also send misleading responses. Loopback, strict Host, Origin and Sec-Fetch checks remain enabled in both modes; they do not authenticate the server to the client. + All executable operations are denied unless granted. The setup grants write the manifest, the lock, the cache, a new starter directory or the generated provider header; grant them only for a project whose registry you trust. `install` and `restore` use the registry already configured by the owner, the manifest or the default; the operation cannot choose another one. @@ -118,7 +134,8 @@ operation of `webfront.start`, not one MCP tool per callback, so the tool list s Each instance has its own URL, so several applications run side by side and the agent picks one by its URL. - **Token.** Every request carries `Authorization: Bearer `, a 256-bit value from the OS, compared in constant time before the body is parsed; otherwise 401 with `WWW-Authenticate: Bearer` (no OAuth server is announced). The token lives as - long as the session: closing it, a deadline or a lost window closes the listener and removes the file. + long as the session by default: closing it, a deadline or a lost window closes the listener and removes the file. A supplied + `mcpToken` remains valid across launches until the application changes it; authentication can be explicitly disabled. - **Client configuration.** `mcp.json` (mode 0600 in a 0700 directory on POSIX, owner-only ACL on Windows) holds the URL and the header, ready for a client that takes a configuration file (`claude --mcp-config PATH/mcp.json`). The token appears in no page, URL, command line, log, banner or discovery record. Never copy it into the project, its `.mcp.json` included: the diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index e9f263ca..92bf6fd2 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -17,6 +17,7 @@ these entries stays in the GitHub releases and the Git history. - The CEF profile is now `cef_cache/`, not `cef_cache`: an application starts with an empty profile (localStorage, cookies); to keep the data, move the old contents of `cef_cache` into `cef_cache/` once (#617, `docs/HOST_INTEGRATION.md`). ### Added +- Configure a stable MCP port and application-supplied Bearer token, or explicitly disable authentication for trusted development (#637, ADR-026, `docs/AUTOMATION.md`). - Connect an MCP client to the application itself: `enableAutomation(app, {.grants = {...}})` serves MCP over Streamable HTTP on a loopback port of its own, prints its URL and writes a private `mcp.json` with the URL and a session Bearer token, so several applications run side by side with no other program (#632, ADR-025, `docs/AUTOMATION.md`). - Use a custom network provider with `DeveloperAppWithNetwork`. The `BasicDeveloperApp` alias selects the existing TCP provider (#631). - Serve HTTPS and WSS with the optional header-only TLS 1.3 listener and reload its PEM identity after renewal (#631, `docs/TLS.md`). diff --git a/docs/DEVELOPING_WITH_AGENTS.md b/docs/DEVELOPING_WITH_AGENTS.md index 4c2be048..2e7d8461 100644 --- a/docs/DEVELOPING_WITH_AGENTS.md +++ b/docs/DEVELOPING_WITH_AGENTS.md @@ -63,6 +63,8 @@ argument. The [developer environment reference](DEVELOPER_ENVIRONMENT.md) has th ## Running wf yourself, through MCP +For a client configured once, the application can set a fixed `mcpPort` and provide the same `mcpToken` on each launch. Copy the first private `mcp.json` URL and Bearer header into the client user configuration, outside the project. Start the application before connecting. This opt-in mode accepts the local server impersonation risk described in [AUTOMATION.md](AUTOMATION.md); the default remains a fresh session token. + The application runs the same commands in its own window and serves them over MCP: in a development build, it is the MCP server, at a URL of its own. An MCP client connects to that URL; no other program is built or launched. @@ -92,7 +94,7 @@ for a project whose output you accept to regenerate. WebFront MCP (grants: check, build, ...): http://127.0.0.1:PORT/mcp - client configuration: /home/me/.local/state/webfront/sessions/SESSION/mcp.json ``` -Each running instance has its own port, so the URL is printed rather than known in advance. `mcp.json` is the client +By default each running instance has its own port, so the URL is printed rather than known in advance. `mcp.json` is the client configuration of that instance, URL and Bearer token together, in a private directory outside the project: ```json diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index 9e226709..cd305596 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -47,6 +47,8 @@ WebFront is a header-only C++23 HTTP/WebSocket core plus a standalone developer `mcp.json` client configuration; no other program is built or launched ([ADR-025](adr/ADR-025-mcp-http-dans-l-application.md), #632). Native grants select check/build/test/preview, bounded inspection, semantic actions, the setup operations and the owner's allow-listed callbacks (`call`). Several instances run side by side, each with its own URL and discovery record. + A fixed MCP port and application-supplied token can keep a client configuration stable; authentication can also be + explicitly disabled for development, with the local-process risks described in [Automation](AUTOMATION.md) (#637). Remote access is out of scope and automation does not compile with `WEBFRONT_DISTRIBUTION`. This does not isolate untrusted project code. [Automation](AUTOMATION.md) documents the listener, lifecycle, limits and the supported MCP profile. The `webfront-agent` launcher, its JSON CLI and MCP on stdio were removed. Known limitation until the next environment diff --git a/docs/adr/ADR-026-configuration-mcp-persistante.md b/docs/adr/ADR-026-configuration-mcp-persistante.md new file mode 100644 index 00000000..c8e6173f --- /dev/null +++ b/docs/adr/ADR-026-configuration-mcp-persistante.md @@ -0,0 +1,23 @@ +# ADR-026 : Configuration MCP stable en développement + +## Versions + +| Version | Date | État | Auteur | Évolution | Révision Git | +| --- | --- | --- | --- | --- | --- | +| 1.0 | 2026-11-22 | Proposée | Ambroise Leclerc | Configuration persistante par projet (#637). | — | +| 1.1 | 2026-11-22 | Acceptée, puis suspendue | Ambroise Leclerc | L'usurpation de l'écouteur révèle une exposition du jeton persistant. | — | +| 1.2 | 2026-11-22 | Acceptée (livraison en cours) | Ambroise Leclerc | Mode explicite simplifié, compromis de sécurité acceptés ; issue #637 amendée. | #637 | + +## Décision + +Le mode de l'ADR-025 reste le défaut : port choisi par l'OS, jeton aléatoire par session et configuration privée supprimée à la fermeture. L'application peut fixer le port et fournir un jeton Bearer durable, ou désactiver explicitement l'authentification. Le développeur gère le secret et sa rotation ; WebFront ne le persiste pas hors de la configuration privée de session. Le client copie une fois URL et en-tête dans sa configuration utilisateur, hors projet. Il doit lancer l'application avant de se connecter. Un port occupé provoque une erreur explicite ; une autre instance peut utiliser le mode par défaut. La découverte ne contient pas de jeton. + +Ces options concernent uniquement le développement : l'automatisation reste exclue des builds de distribution. L'écoute reste sur loopback ; Host, Origin et Sec-Fetch-* restent vérifiés. Un jeton configuré est comparé en temps constant. Les valeurs malformées et les combinaisons ambiguës sont refusées. + +## Conséquences + +Un autre utilisateur local peut occuper le port pendant l'arrêt de l'application et récupérer un Bearer durable envoyé par le client : ce jeton restera utilisable jusqu'à rotation. Sans authentification, tout processus local pouvant joindre le port peut exercer les grants. Un serveur usurpé peut également renvoyer des réponses mensongères au client. Ces limites sont acceptées uniquement sur choix explicite. Host et Origin protègent contre les requêtes de pages web, pas contre ces processus. Un challenge non standard exigerait un client compatible ; le Bearer fonctionne avec les clients MCP ordinaires. + +## Validation + +Relancer l'application deux fois avec la même configuration cliente et appeler initialize puis webfront.session, avec le client HTTP du dépôt et le SDK 2.3.0 s'il est disponible. Vérifier les refus, les instances concurrentes, le conflit de port, l'absence de secret dans la découverte et les protections réseau dans les modes authentifié et sans authentification. Maintenir les guides et AgentGuidance. diff --git a/docs/adr/README.md b/docs/adr/README.md index 98cda27f..74e5fdca 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -1,7 +1,7 @@ # WebFront architecture decision records This directory describes WebFront’s architectural choices and the constraints to preserve -when making changes or generating code. It contains **25 ADRs**, with unique numbers. +when making changes or generating code. It contains **26 ADRs**, with unique numbers. The accepted baseline corresponds to commit `b031ab5` dated **2026-10-19**; the developer environment proposals are dated **2026-10-20**, the direct frontend access proposal **2026-10-24**, the DOM access proposal **2026-10-26**, the developer automation proposal **2026-10-28**, accepted **2026-10-29**, the system services proposal **2026-10-31**, and the developer environment publication proposal **2026-11-02**. Each ADR is versioned @@ -68,6 +68,7 @@ verification evidence remain in [PROJECT_STATUS](../PROJECT_STATUS.md). | [ADR-023](ADR-023-espace-de-noms-des-commandes-du-terminal.md) | Terminal command names: `wf` stays the prefix of project commands, read-only file commands (`ls`, `cat`, `tree`, `mounts`), file command names reserved ahead, dependency graph with `wf list --tree`, `wf why`, `wf info` | Accepted | 2026-11-14 | 1.0 — 2026-11-14 | | [ADR-024](ADR-024-tls-integre.md) | Optional integrated TLS 1.3 server | Proposed | 2026-11-21 | 1.0 | | [ADR-025](ADR-025-mcp-http-dans-l-application.md) | The application serves MCP over Streamable HTTP on its own loopback listener, with a session Bearer token, strict Host/Origin checks, per-instance discovery and no automation in distribution builds; the webfront-agent launcher is removed; amends ADR-019 | Accepted (delivery in progress) | 2026-11-21 | 1.3 — 2026-11-22 | +| [ADR-026](ADR-026-configuration-mcp-persistante.md) | Stable MCP client configuration with explicit development security modes | Accepted (delivery in progress) | 2026-11-22 | 1.2 — 2026-11-22 | Numbering follows the reading topics; milestones and individual file histories provide the chronology, which does not follow the numerical order. @@ -113,7 +114,7 @@ Do not replace historical dates with the date of an editorial change to the docu Keep previous rows and update the current version in the index. - Use one `ADR-NNN-description.md` file per decision and one row in this index. The next number - is **ADR-026**. Retain historical numbers and files. + is **ADR-027**. Retain historical numbers and files. - For a new decision that has not been integrated, use **Proposée** (Proposed), its actual proposal date and validation criteria; do not assign an artificial historical commit date. - After integration, record the date and supporting commits, the accepted negative diff --git a/include/webfront/automation/Enable.hpp b/include/webfront/automation/Enable.hpp index 37d4c0ef..bee5bd5a 100644 --- a/include/webfront/automation/Enable.hpp +++ b/include/webfront/automation/Enable.hpp @@ -79,6 +79,10 @@ struct AutomationOptions { /// The port of the MCP listener: 0 (the default) lets the OS choose; a chosen port is never replaced, its being taken /// makes the activation throw. unsigned short mcpPort = 0; + /// Optional durable Bearer token, supplied by the application; absent selects a random token per session. + std::optional mcpToken{}; + /// Explicitly allow local MCP clients without a token. Development only. + bool disableMcpAuthentication = false; /// A new private directory outside the project that receives the client configuration (`mcp.json`). Empty (the /// default), a directory named after the session is created in the discovery directory. std::filesystem::path directory{}; @@ -119,7 +123,7 @@ class Automation { : session(make(app, options)), discoveryDirectory(options.discovery.empty() ? discovery::defaultDirectory() : options.discovery), privateDirectory(channel::outsideProject(*session, privateDirectoryFor(options, discoveryDirectory, *session))), - mcp(session, privateDirectory.path, options.mcpPort), + mcp(session, privateDirectory.path, options.mcpPort, options.mcpToken, !options.disableMcpAuthentication), registration(discoveryDirectory, record(*session, privateDirectory.path, mcp)), grants(std::move(options.grants)), callbackNames(std::move(options.callbacks)), diff --git a/include/webfront/automation/McpHttp.hpp b/include/webfront/automation/McpHttp.hpp index f421f15c..62453708 100644 --- a/include/webfront/automation/McpHttp.hpp +++ b/include/webfront/automation/McpHttp.hpp @@ -157,7 +157,7 @@ struct Screening { /// Decides on the headers of a request, before its body is read: path, `Host`, `Origin` and `Sec-Fetch-*`, method, /// the Bearer token, then the media types and the announced length of a `POST`. `port` is the listener's own. -inline Screening screen(const http::Request& request, unsigned short port, std::string_view token) { +inline Screening screen(const http::Request& request, unsigned short port, std::string_view token, bool authentication = true) { using detail::lower; // DNS rebinding: a name that resolves to 127.0.0.1 still carries its own Host. Only the two loopback spellings pass. const auto host = detail::single(request, "Host"); @@ -166,7 +166,9 @@ inline Screening screen(const http::Request& request, unsigned short port, std:: return {.refusal = refusal(421, "This listener answers 127.0.0.1 and localhost only")}; // A browser sends Origin on every POST, and Sec-Fetch-* on every request it makes: no web page may reach the route, // the application's own page included. A native MCP client sends neither. - if (detail::present(request, "Origin") || detail::present(request, "Sec-Fetch-Site") || detail::present(request, "Sec-Fetch-Mode")) + if (detail::present(request, "Origin") || std::ranges::any_of(request.headers, [](const auto& header) { + return detail::lower(header.name).starts_with("sec-fetch-"); + })) return {.refusal = refusal(403, "Requests from web pages are refused")}; if (request.uri != "/mcp") return {.refusal = refusal(404, "Not found")}; @@ -178,8 +180,8 @@ inline Screening screen(const http::Request& request, unsigned short port, std:: return {.refusal = std::move(answer)}; } const auto authorization = detail::single(request, "Authorization"); - bool authorized = false; - if (authorization && !authorization->empty()) { + bool authorized = !authentication; + if (authentication && authorization && !authorization->empty()) { const auto space = authorization->find(' '); if (space != std::string::npos && lower(authorization->substr(0, space)) == "bearer") authorized = channel::sameToken(detail::trimmed(std::string_view(*authorization).substr(space + 1)), token); @@ -336,12 +338,11 @@ class Endpoint { }; /// The client configuration of an instance: its URL and its token. `name` names the server for the client. -inline std::string clientConfiguration(std::string_view url, std::string_view token, std::string_view name = "webfront") { - const auto server = objectJson({ - { "type", json::quote("http")}, - { "url", json::quote(url)}, - {"headers", objectJson({{"Authorization", json::quote("Bearer " + std::string(token))}})}, - }); +inline std::string clientConfiguration(std::string_view url, std::string_view token, std::string_view name = "webfront", bool authentication = true) { + std::map fields{{"type", json::quote("http")}, {"url", json::quote(url)}}; + if (authentication) + fields.emplace("headers", objectJson({{"Authorization", json::quote("Bearer " + std::string(token))}})); + const auto server = objectJson(fields); return "{\n \"mcpServers\": {\n " + json::quote(name) + ": " + server + "\n }\n}\n"; } @@ -352,16 +353,17 @@ class Server { public: /// @param port 0 (the default) lets the OS choose; a chosen port is never replaced: when it is taken the constructor throws /// @throws std::system_error naming the address, the port and the cause when the listener cannot be bound - Server(std::shared_ptr controller, const std::filesystem::path& directory, unsigned short port = 0) + Server(std::shared_ptr controller, const std::filesystem::path& directory, unsigned short port = 0, + std::optional fixedToken = std::nullopt, bool authentication = true) : backend(std::move(controller)), endpoint(*backend), listener(channel::createSocket()), - token(channel::nonce()), + token(selectToken(fixedToken, authentication)), boundPort(bind(listener, port)), address("http://127.0.0.1:" + std::to_string(boundPort) + "/mcp"), - file(directory / configurationFile) { + file(directory / configurationFile), authenticate(authentication) { channel::nonblocking(listener.value); - channel::writeEndpoint(file, clientConfiguration(address, token)); + channel::writeEndpoint(file, clientConfiguration(address, token, "webfront", authenticate)); worker = std::jthread([this](std::stop_token stop) { try { serve(stop); @@ -405,6 +407,7 @@ class Server { unsigned short boundPort; std::string address; std::filesystem::path file; + bool authenticate; std::once_flag withdrawn; std::jthread worker; @@ -429,6 +432,15 @@ class Server { } }; + static std::string selectToken(const std::optional& fixed, bool authentication) { + if (!authentication && fixed) + throw std::invalid_argument("A fixed MCP token cannot be combined with disabled authentication"); + if (!fixed) + return authentication ? channel::nonce() : std::string{}; + if (fixed->empty() || fixed->size() > 1024 || !std::ranges::all_of(*fixed, [](unsigned char c) { return c >= 0x21 && c <= 0x7e; })) + throw std::invalid_argument("MCP token must contain 1 to 1024 visible ASCII characters without spaces"); + return *fixed; + } void withdraw() noexcept { // A reader on Windows (readEndpoint does not share deletion) delays the removal briefly; it is retried. std::call_once(withdrawn, [this] { @@ -488,7 +500,7 @@ class Server { refuse(peer, refusal(400, "Malformed HTTP request")); return false; } - auto screening = screen(peer.request, boundPort, token); + auto screening = screen(peer.request, boundPort, token, authenticate); if (screening.refusal) { refuse(peer, *screening.refusal); return false; diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index 759a1955..ab6c9be0 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -42,7 +42,7 @@ "js/developer/environment/embed.mjs": "3d3b5036c34c23a1fa0512c1eea42f26d5f30e054545b61fe83a5c378b74e09e", "examples/life/ui/main.tsx": "7b1ff285d2a6b8f897ef12df872886e61ef4b24e2358a9423b76b38ab75c85d3", "examples/life/ui/style.css": "ac13886f0aea2adfdca21c487467a8f6e647feffb88c51d81766e628584ea5cd", - "js/developer/starters/agent-guide.md": "622a9ca135d223bc7f9f80d99ca975c0597c22b1e5a6fce11372ceff79ab0236", + "js/developer/starters/agent-guide.md": "45dcbcb06cd6c04e048a6fcb9eb4305efde169f97b1c2bafbcc8c127127077f0", "js/developer/starters/app/main.ts": "b4f43fd3cd9136d86dd3e6e89e29092ddf3b67066c2cc08d78078d15a445054e", "js/developer/starters/app/style.css": "6a042eff15ee9b1603c95d3e4e974a03876e1c365389553e84eb7c472aded180", "js/developer/tools/distribution.json": "c9e97f0eaa010e595575e75eba04084d6156baf0d52d1bded02428a017ec3e9f", diff --git a/js/developer/starters/agent-guide.md b/js/developer/starters/agent-guide.md index e9b77d3c..5449e335 100644 --- a/js/developer/starters/agent-guide.md +++ b/js/developer/starters/agent-guide.md @@ -51,6 +51,8 @@ wf dev ui/main.ts # then wf check, wf test and wf embed as above ## Run wf yourself, through MCP +To configure a client once, the application can set a fixed `mcpPort` and provide the same `mcpToken` on each launch. Copy the first private `mcp.json` URL and Bearer header into the client user configuration, outside the project. Start the application before connecting. This opt-in accepts the local server impersonation risk described in `docs/AUTOMATION.md`; the default uses a fresh session token. + Do not ask a person to type these commands and paste their output. The application runs them in its own window and serves them over MCP at a URL of its own: it is the MCP server, no other program is needed. diff --git a/test/cmake/CheckAgentGuide.cmake b/test/cmake/CheckAgentGuide.cmake index 9ab7867e..91c08dec 100644 --- a/test/cmake/CheckAgentGuide.cmake +++ b/test/cmake/CheckAgentGuide.cmake @@ -52,7 +52,7 @@ endif() foreach(text guide page) foreach(needle "ui/" "wf dev" "documentRoot" "app.bootstrap(\"developer\")" "enableAutomation" "webfront.start" "webfront.result" "not\nthe name of your project" "http://127.0.0.1:PORT/mcp" "mcp.json" "Bearer" - "webfront.cancel" "claude --mcp-config") + "webfront.cancel" "claude --mcp-config" "mcpPort" "mcpToken") string(REPLACE "\n" " " flat "${${text}}") string(REPLACE "\n" " " flat_needle "${needle}") _require("${flat}" "${flat_needle}" "${text}") diff --git a/test/tools/AutomationClient.py b/test/tools/AutomationClient.py index 26bea1a5..66c9685e 100644 --- a/test/tools/AutomationClient.py +++ b/test/tools/AutomationClient.py @@ -563,13 +563,44 @@ def session(args): print("MCP real-window regression passed: diagnostics/correction/check/build/test/preview/actions/cancellation/shared session/setup") +def stable(args): + pathlib.Path(args.work).mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(dir=args.work, prefix="stable-") as temporary: + root = pathlib.Path(temporary) + project = root / "project" + shutil.copytree(args.fixture, project) + install(args, project) + with socket.socket() as reservation: + reservation.bind(("127.0.0.1", 0)) + port = reservation.getsockname()[1] + client, original = None, None + with (root / "stable.log").open("w") as log: + for run in range(2): + host = Host(args, project, root, f"stable-{run}", log, ["--stable-mcp", "true", "--mcp-port", str(port)]) + try: + path = pathlib.Path(host.record()["configuration"]) + if client is None: + original = path.read_bytes() + client = Client(path) + else: + assert path.read_bytes() == original + client.mcp_session = None + client.initialize() + assert client.tool("session")["session"] == client.session + client.close() + host.stop() + assert host.wait() == 0, host.logs() + finally: + host.close() + + def main(): parser = argparse.ArgumentParser() for name in ("host", "driver", "environment", "provision", "registry", "fixture", "work"): parser.add_argument("--" + name, required=True) - parser.add_argument("--scenario", choices=("session", "mcp-watchdog", "consumer"), default="session") + parser.add_argument("--scenario", choices=("session", "mcp-watchdog", "consumer", "stable"), default="session") args = parser.parse_args() - {"session": session, "mcp-watchdog": watchdog, "consumer": consumer}[args.scenario](args) + {"session": session, "mcp-watchdog": watchdog, "consumer": consumer, "stable": stable}[args.scenario](args) if __name__ == "__main__": diff --git a/test/unit/AutomationMcpHttpTests.cpp b/test/unit/AutomationMcpHttpTests.cpp index f21c39a6..84ca1bac 100644 --- a/test/unit/AutomationMcpHttpTests.cpp +++ b/test/unit/AutomationMcpHttpTests.cpp @@ -604,3 +604,55 @@ const Scenario mcpHttpActivation{"An application that enables automation serves }); }); }}; + +const Scenario stableMcp{"A fixed MCP token and port survive activation and authentication can be explicitly disabled", [] { + using namespace mcphttptests; + webfront::test::TemporaryDirectory root; + std::filesystem::create_directory(root.path() / "project"); + HttpConsumerApp app{.project = root.path() / "project"}; + const auto sessions = root.path() / "sessions"; + const std::string fixed(64, 'a'); + auto first = enableAutomation(app, {.mcpToken = fixed, .discovery = sessions, .announce = false}); + const auto port = static_cast(std::stoi(first->mcpUrl().substr(first->mcpUrl().rfind(':') + 1))); + const auto config = channel::readEndpoint(first->directory(), "mcp.json"); + first->close(); + for (int run = 0; run < 2; ++run) { + auto instance = enableAutomation(app, {.mcpPort = port, .mcpToken = fixed, .discovery = sessions, .announce = false}); + require(channel::readEndpoint(instance->directory(), "mcp.json") == config); + for (const auto& entry : discovery::list(sessions)) { + std::ifstream input(sessions / (entry.session + ".json")); + std::ostringstream record; + record << input.rdbuf(); + require(record.str().find(fixed) == std::string::npos); + } + const auto opened = roundTrip(port, post(port, initialize, {}, fixed)); + require(opened.status == 200); + require(roundTrip(port, post(port, initialize, {}, std::string(64, 'b'))).status == 401); + const auto extra = "MCP-Session-Id: " + opened.header("mcp-session-id") + "\r\nMCP-Protocol-Version: 2025-11-25\r\n"; + require(roundTrip(port, post(port, initialized, extra, fixed)).status == 202); + const auto result = roundTrip(port, post(port, R"({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"webfront.session","arguments":{}}})", extra, fixed)); + require(result.status == 200); + require(result.body.find("result") != std::string::npos); + requireThrows([&] { enableAutomation(app, {.mcpPort = port, .mcpToken = fixed, .discovery = sessions, .announce = false}); }); + auto side = enableAutomation(app, {.discovery = sessions, .announce = false}); + require(side->mcpUrl() != instance->mcpUrl()); + side->close(); + instance->close(); + } + auto open = enableAutomation(app, {.mcpPort = port, .disableMcpAuthentication = true, .discovery = sessions, .announce = false}); + const Object configuration{channel::readEndpoint(open->directory(), "mcp.json")}; + require(!Object(Object(configuration.raw("mcpServers")).raw("webfront")).has("headers")); + auto request = post(port, initialize); + request.erase(request.find("Authorization:"), request.find("\r\n", request.find("Authorization:")) + 2 - request.find("Authorization:")); + require(roundTrip(port, request).status == 200); + require(roundTrip(port, post(port, initialize, "Origin: http://evil.test\r\n")).status == 403); + require(roundTrip(port, post(port, initialize, "Sec-Fetch-Mode: cors\r\n")).status == 403); + require(roundTrip(port, post(port, initialize, "Sec-Fetch-Dest: document\r\n")).status == 403); + auto hostile = request; + hostile.replace(hostile.find("127.0.0.1"), 9, "evil.test"); + require(roundTrip(port, hostile).status == 421); + open->close(); + requireThrows([&] { enableAutomation(app, {.mcpToken = "", .discovery = sessions, .announce = false}); }); + requireThrows([&] { enableAutomation(app, {.mcpToken = "abc\r\nInjected", .discovery = sessions, .announce = false}); }); + requireThrows([&] { enableAutomation(app, {.mcpToken = fixed, .disableMcpAuthentication = true, .discovery = sessions, .announce = false}); }); +}}; diff --git a/test/web/AutomationHost.cpp b/test/web/AutomationHost.cpp index 611effcd..b13ec321 100644 --- a/test/web/AutomationHost.cpp +++ b/test/web/AutomationHost.cpp @@ -82,6 +82,8 @@ int main(int argc, char** argv) { std::filesystem::path project, environment, registry, directory, sessions, called; std::string integrity, manifest, grants = "check,build,preview,inspect,interact,call", callbacks = "consumer.render"; std::chrono::seconds timeout{30}, startupTimeout{90}; + unsigned short mcpPort = 0; + bool stableMcp = false; for (int i = 1; i + 1 < argc; i += 2) { const std::string_view name{argv[i]}; const std::string value{argv[i + 1]}; @@ -99,6 +101,10 @@ int main(int argc, char** argv) { directory = value; else if (name == "--sessions") sessions = value; + else if (name == "--mcp-port") + mcpPort = static_cast(std::stoul(value)); + else if (name == "--stable-mcp") + stableMcp = value == "true"; else if (name == "--called") called = value; else if (name == "--grants") @@ -144,6 +150,8 @@ int main(int argc, char** argv) { auto automation = webfront::automation::enableAutomation(app, {.grants = split(grants), .callbacks = called.empty() ? std::vector{} : split(callbacks), + .mcpPort = mcpPort, + .mcpToken = stableMcp ? std::optional{std::string(64, 'a')} : std::nullopt, .directory = directory, .discovery = sessions, .timeout = timeout, diff --git a/test/web/CMakeLists.txt b/test/web/CMakeLists.txt index 58efce69..6761391d 100644 --- a/test/web/CMakeLists.txt +++ b/test/web/CMakeLists.txt @@ -185,6 +185,8 @@ if(_browser_tests_available) webfront_add_automation_test(${_case} "automation-${_scenario}" 240 AutomationClient.py --scenario "${_scenario}" --fixture "${_automation_project}" --work "${CMAKE_CURRENT_BINARY_DIR}/automation-${_scenario}") endforeach() + webfront_add_automation_test(AutomationStableMcp automation-stable 240 AutomationClient.py --scenario stable + --fixture "${_automation_project}" --work "${CMAKE_CURRENT_BINARY_DIR}/automation-stable") # Two applications side by side, each driven through its own URL, with the application's own callback (#501, #632). webfront_add_automation_test(AutomationConsumerWindow automation-consumer 240 AutomationClient.py --scenario consumer --fixture "${PROJECT_SOURCE_DIR}/test/fixtures/consumer-project" --work "${CMAKE_CURRENT_BINARY_DIR}/automation-consumer") From 69f5eb3db447de8e989d3efc4a56f373d6b27859 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:13:20 +0100 Subject: [PATCH 02/10] Advance developer environment sources to 1.0.3 --- docs/PROJECT_STATUS.md | 8 +++----- js/developer/environment/bundles.json | 2 +- js/developer/tools/distribution.json | 2 +- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index cd305596..4195576e 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -51,11 +51,9 @@ WebFront is a header-only C++23 HTTP/WebSocket core plus a standalone developer explicitly disabled for development, with the local-process risks described in [Automation](AUTOMATION.md) (#637). Remote access is out of scope and automation does not compile with `WEBFRONT_DISTRIBUTION`. This does not isolate untrusted project code. [Automation](AUTOMATION.md) documents the listener, lifecycle, limits and the supported MCP profile. - The `webfront-agent` launcher, its JSON CLI and MCP on stdio were removed. Known limitation until the next environment - release: the published environment 1.0.1 that the library pins still tells agents (`wf help agents`, the `AGENTS.md` - that `wf create` writes) to run `webfront-agent`, which no longer exists, so that agent path is not ready from a pinned - environment. The replacement texts, which name the application's MCP URL and its `mcp.json`, are in the sources - (environment 1.0.2) and in `docs/DEVELOPING_WITH_AGENTS.md`, which an agent should follow meanwhile. First-contact + The `webfront-agent` launcher, its JSON CLI and MCP on stdio were removed. The pinned environment 1.0.2 describes MCP; + the starter guidance for stable client configuration is in the 1.0.3 sources and will reach `wf create` in the next + environment release. Until then agents can follow `docs/DEVELOPING_WITH_AGENTS.md`. First-contact guidance for agents (README section, `docs/DEVELOPING_WITH_AGENTS.md`, `webfront_write_agent_guide()`, configuration and startup notices) comes with the library. - **Maintaining WebFront.** The repository is itself a `wf` project, selected with diff --git a/js/developer/environment/bundles.json b/js/developer/environment/bundles.json index ab6c9be0..8d6e2c8b 100644 --- a/js/developer/environment/bundles.json +++ b/js/developer/environment/bundles.json @@ -45,7 +45,7 @@ "js/developer/starters/agent-guide.md": "45dcbcb06cd6c04e048a6fcb9eb4305efde169f97b1c2bafbcc8c127127077f0", "js/developer/starters/app/main.ts": "b4f43fd3cd9136d86dd3e6e89e29092ddf3b67066c2cc08d78078d15a445054e", "js/developer/starters/app/style.css": "6a042eff15ee9b1603c95d3e4e974a03876e1c365389553e84eb7c472aded180", - "js/developer/tools/distribution.json": "c9e97f0eaa010e595575e75eba04084d6156baf0d52d1bded02428a017ec3e9f", + "js/developer/tools/distribution.json": "cd186e28ede2e43999bea0ffdd16f45cb3347f2d2d2ae01f198448d7237c40b2", "js/developer/tools/archive.mjs": "da63bb9d796ddfd24ed945b15c53f66a0400eb177886fd4f1c8fd10cafb5a91b", "js/developer/tools/distribution.mjs": "43dfdccc912693db46fd095fd78ae79325abab672d99f89fd569914ef3499cad", "js/developer/scripts/build.mjs": "a577f4396ab867096bc6fe6876e16e5220121ec8e8dd234fa1e4819d0a1173e1", diff --git a/js/developer/tools/distribution.json b/js/developer/tools/distribution.json index e8f4a76a..db7c0689 100644 --- a/js/developer/tools/distribution.json +++ b/js/developer/tools/distribution.json @@ -1,4 +1,4 @@ { - "version": "1.0.2", + "version": "1.0.3", "baseUrl": "https://dist.webfront.fr/" } From 9205c6ff2dbd427b6e32db710430b1e48113b2db Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:26:24 +0100 Subject: [PATCH 03/10] Harden fixed MCP credentials and retry port conflicts --- docs/AUTOMATION.md | 4 +- docs/CHANGELOG.md | 1 + .../ADR-026-configuration-mcp-persistante.md | 2 + include/webfront/automation/McpHttp.hpp | 8 +-- test/tools/AutomationClient.py | 52 +++++++++++-------- test/unit/AutomationMcpHttpTests.cpp | 10 +++- test/web/AutomationHost.cpp | 14 ++++- 7 files changed, 63 insertions(+), 28 deletions(-) diff --git a/docs/AUTOMATION.md b/docs/AUTOMATION.md index eef2c907..fcd91fce 100644 --- a/docs/AUTOMATION.md +++ b/docs/AUTOMATION.md @@ -71,10 +71,12 @@ auto automation = webfront::automation::enableAutomation( app, {.grants = {"check", "build"}, .mcpPort = 19002, .mcpToken = std::string{token}}); ``` -The application includes ``, `` and `` for this example. A configured token must be 1–1024 visible ASCII characters without spaces. To opt in to an unauthenticated listener instead, use `.disableMcpAuthentication = true` and omit `mcpToken`; its client configuration has no Authorization header. +The application includes ``, `` and `` for this example. A configured token must be 32–1024 visible ASCII characters without spaces; length alone does not guarantee randomness. To opt in to an unauthenticated listener instead, use `.disableMcpAuthentication = true` and omit `mcpToken`; its client configuration has no Authorization header. In that mode any Authorization header, including an incorrect Bearer, is ignored. These options are for trusted development environments. A different local user can occupy the fixed port while the application is stopped and receive a durable Bearer sent by the client, then reuse it when the application starts. Without authentication, any local process that reaches the listener can exercise its grants. A fake server can also send misleading responses. Loopback, strict Host, Origin and Sec-Fetch checks remain enabled in both modes; they do not authenticate the server to the client. +After a crash or forced termination, the private `mcp.json` can remain on disk with the durable token. Session discovery prunes known files in default session directories when it detects a dead process, but cleanup can be delayed or fail; an explicitly supplied `directory` is not pruned by discovery. Inspect and remove stale private files as needed, and rotate a token if it may have been exposed. + All executable operations are denied unless granted. The setup grants write the manifest, the lock, the cache, a new starter directory or the generated provider header; grant them only for a project whose registry you trust. `install` and `restore` use the registry already configured by the owner, the manifest or the default; the operation cannot choose another one. diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 92bf6fd2..4bf27cb1 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -26,6 +26,7 @@ these entries stays in the GitHub releases and the Git history. - Run the MSVC code analysis in a pull request into `develop` that changes Windows code, and list the reruns each job needed before going green with `FlakeReport.py --days` (#628, `docs/TEST_TIERS.md`, `docs/TEST_PERFORMANCE.md`). ### Fixed +- Refuse every `Sec-Fetch-*` request header on the MCP listener, including `Sec-Fetch-Dest`, in both authenticated and unauthenticated modes (#637). - Pass the compiler analysis on the Windows pseudoterminal when it cannot prove the attribute list non-null (C6387), stop a unit test from opening the developer's real browser (the directory of its replacement opener was removed before the shell found it), and keep an accepted connection whose `TCP_NODELAY` the system refuses, as macOS does after a reset (#628). ## [1.1.0] - 2026-11-20 diff --git a/docs/adr/ADR-026-configuration-mcp-persistante.md b/docs/adr/ADR-026-configuration-mcp-persistante.md index c8e6173f..39cef934 100644 --- a/docs/adr/ADR-026-configuration-mcp-persistante.md +++ b/docs/adr/ADR-026-configuration-mcp-persistante.md @@ -18,6 +18,8 @@ Ces options concernent uniquement le développement : l'automatisation reste exc Un autre utilisateur local peut occuper le port pendant l'arrêt de l'application et récupérer un Bearer durable envoyé par le client : ce jeton restera utilisable jusqu'à rotation. Sans authentification, tout processus local pouvant joindre le port peut exercer les grants. Un serveur usurpé peut également renvoyer des réponses mensongères au client. Ces limites sont acceptées uniquement sur choix explicite. Host et Origin protègent contre les requêtes de pages web, pas contre ces processus. Un challenge non standard exigerait un client compatible ; le Bearer fonctionne avec les clients MCP ordinaires. +Après un crash ou un arrêt forcé, le fichier privé de session peut rester sur disque avec le jeton durable. La découverte tente de nettoyer les répertoires de session par défaut lorsque le processus n'existe plus ; ce nettoyage peut être différé ou échouer, et ne touche pas un répertoire fourni explicitement. La fermeture propre retire la configuration. L'application ou son propriétaire doit gérer les fichiers résiduels et la rotation du secret si nécessaire. + ## Validation Relancer l'application deux fois avec la même configuration cliente et appeler initialize puis webfront.session, avec le client HTTP du dépôt et le SDK 2.3.0 s'il est disponible. Vérifier les refus, les instances concurrentes, le conflit de port, l'absence de secret dans la découverte et les protections réseau dans les modes authentifié et sans authentification. Maintenir les guides et AgentGuidance. diff --git a/include/webfront/automation/McpHttp.hpp b/include/webfront/automation/McpHttp.hpp index 62453708..267924c0 100644 --- a/include/webfront/automation/McpHttp.hpp +++ b/include/webfront/automation/McpHttp.hpp @@ -357,8 +357,8 @@ class Server { std::optional fixedToken = std::nullopt, bool authentication = true) : backend(std::move(controller)), endpoint(*backend), - listener(channel::createSocket()), token(selectToken(fixedToken, authentication)), + listener(channel::createSocket()), boundPort(bind(listener, port)), address("http://127.0.0.1:" + std::to_string(boundPort) + "/mcp"), file(directory / configurationFile), authenticate(authentication) { @@ -402,8 +402,8 @@ class Server { [[maybe_unused]] channel::Runtime runtime; std::shared_ptr backend; Endpoint endpoint; - channel::Socket listener; std::string token; + channel::Socket listener; unsigned short boundPort; std::string address; std::filesystem::path file; @@ -437,8 +437,8 @@ class Server { throw std::invalid_argument("A fixed MCP token cannot be combined with disabled authentication"); if (!fixed) return authentication ? channel::nonce() : std::string{}; - if (fixed->empty() || fixed->size() > 1024 || !std::ranges::all_of(*fixed, [](unsigned char c) { return c >= 0x21 && c <= 0x7e; })) - throw std::invalid_argument("MCP token must contain 1 to 1024 visible ASCII characters without spaces"); + if (fixed->size() < 32 || fixed->size() > 1024 || !std::ranges::all_of(*fixed, [](unsigned char c) { return c >= 0x21 && c <= 0x7e; })) + throw std::invalid_argument("MCP token must contain 32 to 1024 visible ASCII characters without spaces"); return *fixed; } void withdraw() noexcept { diff --git a/test/tools/AutomationClient.py b/test/tools/AutomationClient.py index 66c9685e..145b7d21 100644 --- a/test/tools/AutomationClient.py +++ b/test/tools/AutomationClient.py @@ -570,28 +570,38 @@ def stable(args): project = root / "project" shutil.copytree(args.fixture, project) install(args, project) - with socket.socket() as reservation: - reservation.bind(("127.0.0.1", 0)) - port = reservation.getsockname()[1] - client, original = None, None with (root / "stable.log").open("w") as log: - for run in range(2): - host = Host(args, project, root, f"stable-{run}", log, ["--stable-mcp", "true", "--mcp-port", str(port)]) - try: - path = pathlib.Path(host.record()["configuration"]) - if client is None: - original = path.read_bytes() - client = Client(path) - else: - assert path.read_bytes() == original - client.mcp_session = None - client.initialize() - assert client.tool("session")["session"] == client.session - client.close() - host.stop() - assert host.wait() == 0, host.logs() - finally: - host.close() + # The reservation must be released before the host binds; retry only a confirmed EADDRINUSE. + for attempt in range(5): + with socket.socket() as reservation: + reservation.bind(("127.0.0.1", 0)) + port = reservation.getsockname()[1] + client, original = None, None + for run in range(2): + host = Host(args, project, root, f"stable-{attempt}-{run}", log, ["--stable-mcp", "true", "--mcp-port", str(port)]) + try: + try: + path = pathlib.Path(host.record()["configuration"]) + except AssertionError: + if host.process.poll() == 73: + break + raise + if client is None: + original = path.read_bytes() + client = Client(path) + else: + assert path.read_bytes() == original + client.mcp_session = None + client.initialize() + assert client.tool("session")["session"] == client.session + client.close() + host.stop() + assert host.wait() == 0, host.logs() + finally: + host.close() + else: + return + raise AssertionError("MCP port was occupied on all five attempts") def main(): diff --git a/test/unit/AutomationMcpHttpTests.cpp b/test/unit/AutomationMcpHttpTests.cpp index 84ca1bac..67fbbcb8 100644 --- a/test/unit/AutomationMcpHttpTests.cpp +++ b/test/unit/AutomationMcpHttpTests.cpp @@ -178,6 +178,7 @@ const Scenario mcpHttpScreening{"MCP HTTP requests are screened on their headers require(status(screened(post(port, "{}", "Origin: http://127.0.0.1:9002\r\n"))) == 403); require(status(screened(post(port, "{}", "Origin: null\r\n"))) == 403); require(status(screened(post(port, "{}", "Sec-Fetch-Site: same-origin\r\n"))) == 403); + require(status(screened(post(port, "{}", "Sec-Fetch-Dest: document\r\n"))) == 403); require(status(screened(post(port, "{}", "Sec-Fetch-Mode: no-cors\r\n"))) == 403); }); then("a CORS preflight and a GET get 405 and no Access-Control header", [&] { @@ -642,9 +643,11 @@ const Scenario stableMcp{"A fixed MCP token and port survive activation and auth auto open = enableAutomation(app, {.mcpPort = port, .disableMcpAuthentication = true, .discovery = sessions, .announce = false}); const Object configuration{channel::readEndpoint(open->directory(), "mcp.json")}; require(!Object(Object(configuration.raw("mcpServers")).raw("webfront")).has("headers")); + require(channel::readEndpoint(open->directory(), "mcp.json").find(fixed) == std::string::npos); auto request = post(port, initialize); request.erase(request.find("Authorization:"), request.find("\r\n", request.find("Authorization:")) + 2 - request.find("Authorization:")); require(roundTrip(port, request).status == 200); + require(roundTrip(port, post(port, initialize, {}, "wrong-token")).status == 200); require(roundTrip(port, post(port, initialize, "Origin: http://evil.test\r\n")).status == 403); require(roundTrip(port, post(port, initialize, "Sec-Fetch-Mode: cors\r\n")).status == 403); require(roundTrip(port, post(port, initialize, "Sec-Fetch-Dest: document\r\n")).status == 403); @@ -653,6 +656,11 @@ const Scenario stableMcp{"A fixed MCP token and port survive activation and auth require(roundTrip(port, hostile).status == 421); open->close(); requireThrows([&] { enableAutomation(app, {.mcpToken = "", .discovery = sessions, .announce = false}); }); - requireThrows([&] { enableAutomation(app, {.mcpToken = "abc\r\nInjected", .discovery = sessions, .announce = false}); }); + requireThrows([&] { enableAutomation(app, {.mcpToken = "a", .discovery = sessions, .announce = false}); }); + requireThrows([&] { enableAutomation(app, {.mcpToken = std::string(31, 'a'), .discovery = sessions, .announce = false}); }); + requireThrows([&] { enableAutomation(app, {.mcpToken = std::string(1025, 'a'), .discovery = sessions, .announce = false}); }); + requireThrows([&] { enableAutomation(app, {.mcpToken = std::string(32, 'a') + "\r\nInjected", .discovery = sessions, .announce = false}); }); requireThrows([&] { enableAutomation(app, {.mcpToken = fixed, .disableMcpAuthentication = true, .discovery = sessions, .announce = false}); }); + auto minimum = enableAutomation(app, {.mcpToken = std::string(32, 'a'), .discovery = sessions, .announce = false}); + minimum->close(); }}; diff --git a/test/web/AutomationHost.cpp b/test/web/AutomationHost.cpp index b13ec321..6559d1bb 100644 --- a/test/web/AutomationHost.cpp +++ b/test/web/AutomationHost.cpp @@ -11,13 +11,15 @@ // `consumer.secret` (never allow-listed by the tests). Closing its standard input closes the window, on every platform and // whatever the engine does with signals. The status is 0 after a normal closing, 70 when the developer environment failed // to start (its reason on stderr), 71 when the native deadline of an operation revoked the session; a window that does not -// close after a deadline ends the process with enableAutomation's own status 72. +// close after a deadline ends the process with enableAutomation's own status 72. An occupied MCP port exits with 73 so +// the test client can retry a port lost between reservation and bind. #include "../driver/WfDriver.hpp" #include #include #include #include +#include #ifndef _WIN32 #include #include @@ -178,6 +180,16 @@ int main(int argc, char** argv) { automation->close(); app.shutdown(); return status; + } catch (const std::system_error& error) { + std::cerr << "automation_host: " << error.what() << '\n'; +#ifdef _WIN32 + const auto addressInUse = WSAEADDRINUSE; +#else + const auto addressInUse = EADDRINUSE; +#endif + if (error.code().value() == addressInUse && std::string_view(error.what()).starts_with("WebFront cannot listen for MCP")) + return 73; + return 1; } catch (const std::exception& error) { std::cerr << "automation_host: " << error.what() << '\n'; return 1; From 5e9008c7ad4b9fbaa0d293709c55437047a18851 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:27:13 +0100 Subject: [PATCH 04/10] Exercise the occupied MCP port retry signal --- test/tools/AutomationClient.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/test/tools/AutomationClient.py b/test/tools/AutomationClient.py index 145b7d21..5f5115dd 100644 --- a/test/tools/AutomationClient.py +++ b/test/tools/AutomationClient.py @@ -571,6 +571,16 @@ def stable(args): shutil.copytree(args.fixture, project) install(args, project) with (root / "stable.log").open("w") as log: + # Exercise the signal used by the retry with a port that is definitely occupied. + with socket.socket() as occupied: + occupied.bind(("127.0.0.1", 0)) + occupied.listen(1) + host = Host(args, project, root, "occupied", log, + ["--stable-mcp", "true", "--mcp-port", str(occupied.getsockname()[1])]) + try: + assert host.wait() == 73, host.logs() + finally: + host.close() # The reservation must be released before the host binds; retry only a confirmed EADDRINUSE. for attempt in range(5): with socket.socket() as reservation: From 72135113227e32b62941b3981fd7a2930436d12a Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:57:54 +0100 Subject: [PATCH 05/10] Handle transient MCP cleanup checks on Windows --- docs/DEVELOPER_ENVIRONMENT.md | 5 +++++ include/webfront/automation/McpHttp.hpp | 13 ++++++++++--- test/unit/AutomationMcpHttpTests.cpp | 17 +++++++++++++---- test/web/AutomationHost.cpp | 4 ++-- 4 files changed, 30 insertions(+), 9 deletions(-) diff --git a/docs/DEVELOPER_ENVIRONMENT.md b/docs/DEVELOPER_ENVIRONMENT.md index 2450bd0e..0e908183 100644 --- a/docs/DEVELOPER_ENVIRONMENT.md +++ b/docs/DEVELOPER_ENVIRONMENT.md @@ -792,6 +792,11 @@ checks the pinned header against the published archive. The headers of the core' `@webfront/developer-environment`, `@webfront/app-starter` and `@webfront/life-starter`. They are distributed as static GitHub Pages downloads; no npm publication or scope ownership is required. +The version in `distribution.json` is the version built from the current sources (currently 1.0.3, not yet published). +It can be ahead of `DeveloperReleaseData.hpp`, which pins the published 1.0.2 environment used by applications. The +compatibility table above records that published pin, not the next source build. The pin changes only when a new +distribution is published and adopted. + The `SelfBuild*` CTest cases run the scripts on a copy of the sources, with the dependencies installed from the local registry: the build, a repeat build (same bytes), the checked-in bootstrap bundles and checksums rebuilt by wf alone (and the core headers rendered from them by CMake), the staging of the site (a second staging repeats the same bytes, a changed diff --git a/include/webfront/automation/McpHttp.hpp b/include/webfront/automation/McpHttp.hpp index 267924c0..9b0c462b 100644 --- a/include/webfront/automation/McpHttp.hpp +++ b/include/webfront/automation/McpHttp.hpp @@ -157,7 +157,7 @@ struct Screening { /// Decides on the headers of a request, before its body is read: path, `Host`, `Origin` and `Sec-Fetch-*`, method, /// the Bearer token, then the media types and the announced length of a `POST`. `port` is the listener's own. -inline Screening screen(const http::Request& request, unsigned short port, std::string_view token, bool authentication = true) { +inline Screening screen(const http::Request& request, unsigned short port, std::string_view token, bool authentication) { using detail::lower; // DNS rebinding: a name that resolves to 127.0.0.1 still carries its own Host. Only the two loopback spellings pass. const auto host = detail::single(request, "Host"); @@ -338,7 +338,7 @@ class Endpoint { }; /// The client configuration of an instance: its URL and its token. `name` names the server for the client. -inline std::string clientConfiguration(std::string_view url, std::string_view token, std::string_view name = "webfront", bool authentication = true) { +inline std::string clientConfiguration(std::string_view url, std::string_view token, std::string_view name, bool authentication) { std::map fields{{"type", json::quote("http")}, {"url", json::quote(url)}}; if (authentication) fields.emplace("headers", objectJson({{"Authorization", json::quote("Bearer " + std::string(token))}})); @@ -346,6 +346,13 @@ inline std::string clientConfiguration(std::string_view url, std::string_view to return "{\n \"mcpServers\": {\n " + json::quote(name) + ": " + server + "\n }\n}\n"; } +/// A failure to bind or listen on the requested MCP port; retains the native error code. +class BindError : public std::system_error { +public: + BindError(std::error_code cause, unsigned short port) + : std::system_error(cause, "WebFront cannot listen for MCP on 127.0.0.1:" + std::to_string(port)) { } +}; + /// The loopback listener. It writes `mcp.json` into `directory` (an existing private directory outside the project) and /// removes it when it stops. Closing the session stops it; so does `stop()`. template @@ -466,7 +473,7 @@ class Server { auto address = channel::address(requested); if (::bind(socket.value, reinterpret_cast(&address), sizeof address) || ::listen(socket.value, 16)) { const std::error_code cause{channel::socketError(), std::system_category()}; - throw std::system_error(cause, "WebFront cannot listen for MCP on 127.0.0.1:" + std::to_string(requested)); + throw BindError(cause, requested); } #ifdef _WIN32 int size = sizeof address; diff --git a/test/unit/AutomationMcpHttpTests.cpp b/test/unit/AutomationMcpHttpTests.cpp index 67fbbcb8..5cc16c08 100644 --- a/test/unit/AutomationMcpHttpTests.cpp +++ b/test/unit/AutomationMcpHttpTests.cpp @@ -146,7 +146,7 @@ struct HttpConsumerApp { const Scenario mcpHttpScreening{"MCP HTTP requests are screened on their headers before any body is read", [] { using namespace mcphttptests; constexpr unsigned short port = 4321; - const auto screened = [&](std::string_view text) { return mcphttp::screen(parsed(text), port, token); }; + const auto screened = [&](std::string_view text) { return mcphttp::screen(parsed(text), port, token, true); }; given("a well-formed authenticated POST", [&] { then("it is accepted with its announced length", [&] { const auto accepted = screened(post(port, "{}")); @@ -471,7 +471,7 @@ const Scenario mcpHttpListener{"The MCP listener serves loopback HTTP with a pri try { mcphttp::Server second{controller, other.path, port}; require(false); - } catch (const std::system_error& error) { + } catch (const mcphttp::BindError& error) { require(std::string(error.what()).find("127.0.0.1:" + std::to_string(port)) != std::string::npos); } require(!std::filesystem::exists(other.path / mcphttp::configurationFile)); @@ -481,9 +481,18 @@ const Scenario mcpHttpListener{"The MCP listener serves loopback HTTP with a pri controller->close("Developer window closed"); then("the listener closes and the configuration with its token is removed", [&] { const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{2}; - while (std::filesystem::exists(server.configuration()) && std::chrono::steady_clock::now() < deadline) + std::error_code error; + bool present = true; + do { + present = std::filesystem::exists(server.configuration(), error); + if (!error && !present) + break; + if (error && !channel::transientRemovalFailure(error)) + break; std::this_thread::sleep_for(std::chrono::milliseconds{10}); - require(!std::filesystem::exists(server.configuration())); + } while (std::chrono::steady_clock::now() < deadline); + require(!error); + require(!present); [[maybe_unused]] channel::Runtime runtime; channel::Socket peer{channel::createSocket()}; const auto address = channel::address(port); diff --git a/test/web/AutomationHost.cpp b/test/web/AutomationHost.cpp index 6559d1bb..5b2a849e 100644 --- a/test/web/AutomationHost.cpp +++ b/test/web/AutomationHost.cpp @@ -180,14 +180,14 @@ int main(int argc, char** argv) { automation->close(); app.shutdown(); return status; - } catch (const std::system_error& error) { + } catch (const webfront::automation::mcphttp::BindError& error) { std::cerr << "automation_host: " << error.what() << '\n'; #ifdef _WIN32 const auto addressInUse = WSAEADDRINUSE; #else const auto addressInUse = EADDRINUSE; #endif - if (error.code().value() == addressInUse && std::string_view(error.what()).starts_with("WebFront cannot listen for MCP")) + if (error.code().value() == addressInUse) return 73; return 1; } catch (const std::exception& error) { From 109652f106632909cba8e21af8b3a07775c6fdaa Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:51:37 +0100 Subject: [PATCH 06/10] Validate MCP options before starting automation --- docs/adr/ADR-025-mcp-http-dans-l-application.md | 2 +- include/webfront/automation/Enable.hpp | 2 ++ include/webfront/automation/McpHttp.hpp | 17 +++++++++++------ test/tools/AutomationClient.py | 2 ++ test/unit/AutomationMcpHttpTests.cpp | 15 ++++++++++++++- 5 files changed, 30 insertions(+), 8 deletions(-) diff --git a/docs/adr/ADR-025-mcp-http-dans-l-application.md b/docs/adr/ADR-025-mcp-http-dans-l-application.md index f192fc86..18433a17 100644 --- a/docs/adr/ADR-025-mcp-http-dans-l-application.md +++ b/docs/adr/ADR-025-mcp-http-dans-l-application.md @@ -104,7 +104,7 @@ Avant l'authentification, et donc même avec un jeton valide : - **Host** doit valoir exactement `127.0.0.1:` ou `localhost:` ; sinon 421. Cela écarte le rebinding DNS. - **Origin** non vide : 403, quelle que soit sa valeur, y compris l'origine de l'application. Un client MCP natif n'envoie - pas d'`Origin` ; un navigateur l'envoie sur tout `POST`. `Sec-Fetch-Site` ou `Sec-Fetch-Mode` présent : 403 aussi. + pas d'`Origin` ; un navigateur l'envoie sur tout `POST`. Tout en-tête `Sec-Fetch-*` présent reçoit aussi 403. - **Content-Type** doit être `application/json` : une requête « simple » de formulaire est refusée (415), et la requête de pré-vérification `OPTIONS` reçoit 405 sans aucun en-tête CORS. Aucune réponse ne porte `Access-Control-Allow-*`. diff --git a/include/webfront/automation/Enable.hpp b/include/webfront/automation/Enable.hpp index bee5bd5a..b168451d 100644 --- a/include/webfront/automation/Enable.hpp +++ b/include/webfront/automation/Enable.hpp @@ -232,6 +232,7 @@ class Automation { privateDirectory.cleanup(); } static std::shared_ptr make(App& app, const AutomationOptions& options) { + mcphttp::validateTokenOptions(options.mcpToken, !options.disableMcpAuthentication); if (options.startupTimeout <= std::chrono::seconds::zero()) throw std::invalid_argument("Automation startupTimeout must be positive"); if (options.closeGrace < std::chrono::milliseconds::zero()) @@ -280,6 +281,7 @@ class Automation { /// `shutdown()`. template std::unique_ptr> enableAutomation(App& app, AutomationOptions options) { + mcphttp::validateTokenOptions(options.mcpToken, !options.disableMcpAuthentication); return std::make_unique>(app, std::move(options)); } } // namespace webfront::automation diff --git a/include/webfront/automation/McpHttp.hpp b/include/webfront/automation/McpHttp.hpp index 9b0c462b..30dae38f 100644 --- a/include/webfront/automation/McpHttp.hpp +++ b/include/webfront/automation/McpHttp.hpp @@ -157,7 +157,7 @@ struct Screening { /// Decides on the headers of a request, before its body is read: path, `Host`, `Origin` and `Sec-Fetch-*`, method, /// the Bearer token, then the media types and the announced length of a `POST`. `port` is the listener's own. -inline Screening screen(const http::Request& request, unsigned short port, std::string_view token, bool authentication) { +inline Screening screen(const http::Request& request, unsigned short port, std::string_view token, bool authentication = true) { using detail::lower; // DNS rebinding: a name that resolves to 127.0.0.1 still carries its own Host. Only the two loopback spellings pass. const auto host = detail::single(request, "Host"); @@ -338,7 +338,7 @@ class Endpoint { }; /// The client configuration of an instance: its URL and its token. `name` names the server for the client. -inline std::string clientConfiguration(std::string_view url, std::string_view token, std::string_view name, bool authentication) { +inline std::string clientConfiguration(std::string_view url, std::string_view token, std::string_view name = "webfront", bool authentication = true) { std::map fields{{"type", json::quote("http")}, {"url", json::quote(url)}}; if (authentication) fields.emplace("headers", objectJson({{"Authorization", json::quote("Bearer " + std::string(token))}})); @@ -346,6 +346,14 @@ inline std::string clientConfiguration(std::string_view url, std::string_view to return "{\n \"mcpServers\": {\n " + json::quote(name) + ": " + server + "\n }\n}\n"; } +/// Validate the selected authentication options before creating session or listener resources. +inline void validateTokenOptions(const std::optional& fixed, bool authentication) { + if (!authentication && fixed) + throw std::invalid_argument("A fixed MCP token cannot be combined with disabled authentication"); + if (fixed && (fixed->size() < 32 || fixed->size() > 1024 || !std::ranges::all_of(*fixed, [](unsigned char c) { return c >= 0x21 && c <= 0x7e; }))) + throw std::invalid_argument("MCP token must contain 32 to 1024 visible ASCII characters without spaces"); +} + /// A failure to bind or listen on the requested MCP port; retains the native error code. class BindError : public std::system_error { public: @@ -440,12 +448,9 @@ class Server { }; static std::string selectToken(const std::optional& fixed, bool authentication) { - if (!authentication && fixed) - throw std::invalid_argument("A fixed MCP token cannot be combined with disabled authentication"); + validateTokenOptions(fixed, authentication); if (!fixed) return authentication ? channel::nonce() : std::string{}; - if (fixed->size() < 32 || fixed->size() > 1024 || !std::ranges::all_of(*fixed, [](unsigned char c) { return c >= 0x21 && c <= 0x7e; })) - throw std::invalid_argument("MCP token must contain 32 to 1024 visible ASCII characters without spaces"); return *fixed; } void withdraw() noexcept { diff --git a/test/tools/AutomationClient.py b/test/tools/AutomationClient.py index 5f5115dd..04e01fbb 100644 --- a/test/tools/AutomationClient.py +++ b/test/tools/AutomationClient.py @@ -594,6 +594,8 @@ def stable(args): path = pathlib.Path(host.record()["configuration"]) except AssertionError: if host.process.poll() == 73: + # On either launch the port may have been taken in the gap; restart both launches + # with a new port and client so each successful pair still uses one configuration. break raise if client is None: diff --git a/test/unit/AutomationMcpHttpTests.cpp b/test/unit/AutomationMcpHttpTests.cpp index 5cc16c08..86157703 100644 --- a/test/unit/AutomationMcpHttpTests.cpp +++ b/test/unit/AutomationMcpHttpTests.cpp @@ -133,13 +133,14 @@ struct HttpConsumerApp { }; std::filesystem::path project; std::vector registered{}; + mutable unsigned projectReads = 0; template void cppFunction(std::string_view name, Handler) { registered.emplace_back(name); } webfront::UISubscription subscribeUIStarted(std::function) { return {}; } webfront::UISubscription subscribeUIClosed(std::function) { return {}; } - const std::filesystem::path& projectDirectory() const { return project; } + const std::filesystem::path& projectDirectory() const { ++projectReads; return project; } }; } // namespace mcphttptests @@ -153,6 +154,9 @@ const Scenario mcpHttpScreening{"MCP HTTP requests are screened on their headers require(!accepted.refusal); require(accepted.length == 2); require(!accepted.expectsContinue); + require(!mcphttp::screen(parsed(post(port, "{}")), port, token).refusal); + const Object defaults{mcphttp::clientConfiguration("http://127.0.0.1:4321/mcp", token)}; + require(Object(Object(defaults.raw("mcpServers")).raw("webfront")).has("headers")); require(screened(post(port, "{}", "Expect: 100-continue\r\n")).expectsContinue); }); then("localhost is the other accepted spelling, and the Bearer scheme is case-insensitive", [&] { @@ -670,6 +674,15 @@ const Scenario stableMcp{"A fixed MCP token and port survive activation and auth requireThrows([&] { enableAutomation(app, {.mcpToken = std::string(1025, 'a'), .discovery = sessions, .announce = false}); }); requireThrows([&] { enableAutomation(app, {.mcpToken = std::string(32, 'a') + "\r\nInjected", .discovery = sessions, .announce = false}); }); requireThrows([&] { enableAutomation(app, {.mcpToken = fixed, .disableMcpAuthentication = true, .discovery = sessions, .announce = false}); }); + HttpConsumerApp untouched{.project = root.path() / "project"}; + const auto absent = root.path() / "never-created"; + requireThrows([&] { enableAutomation(untouched, {.mcpToken = "short", .discovery = absent, .announce = false}); }); + require(untouched.projectReads == 0); + require(untouched.registered.empty()); + require(!std::filesystem::exists(absent)); + requireThrows([&] { Automation invalid{untouched, {.mcpToken = fixed, .disableMcpAuthentication = true, .discovery = absent, .announce = false}}; }); + require(untouched.projectReads == 0); + require(!std::filesystem::exists(absent)); auto minimum = enableAutomation(app, {.mcpToken = std::string(32, 'a'), .discovery = sessions, .announce = false}); minimum->close(); }}; From 0b2c6d24de8e443c30d7eb445e3c3d7fa25f0c84 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 22 Nov 2026 21:29:01 +0100 Subject: [PATCH 07/10] Make unauthenticated MCP sessions visible --- docs/AUTOMATION.md | 2 + docs/PROJECT_STATUS.md | 3 +- .../ADR-026-configuration-mcp-persistante.md | 6 +- include/webfront/automation/Enable.hpp | 5 +- include/webfront/automation/McpHttp.hpp | 9 +- test/unit/AutomationMcpHttpTests.cpp | 122 ++++++++++++------ 6 files changed, 98 insertions(+), 49 deletions(-) diff --git a/docs/AUTOMATION.md b/docs/AUTOMATION.md index fcd91fce..c5f0f80a 100644 --- a/docs/AUTOMATION.md +++ b/docs/AUTOMATION.md @@ -73,6 +73,8 @@ auto automation = webfront::automation::enableAutomation( The application includes ``, `` and `` for this example. A configured token must be 32–1024 visible ASCII characters without spaces; length alone does not guarantee randomness. To opt in to an unauthenticated listener instead, use `.disableMcpAuthentication = true` and omit `mcpToken`; its client configuration has no Authorization header. In that mode any Authorization header, including an incorrect Bearer, is ignored. +The startup banner warns when authentication is disabled. It appears in the developer terminal and on stderr; as with the normal banner, `announce = false` suppresses the stderr copy. + These options are for trusted development environments. A different local user can occupy the fixed port while the application is stopped and receive a durable Bearer sent by the client, then reuse it when the application starts. Without authentication, any local process that reaches the listener can exercise its grants. A fake server can also send misleading responses. Loopback, strict Host, Origin and Sec-Fetch checks remain enabled in both modes; they do not authenticate the server to the client. After a crash or forced termination, the private `mcp.json` can remain on disk with the durable token. Session discovery prunes known files in default session directories when it detects a dead process, but cleanup can be delayed or fail; an explicitly supplied `directory` is not pruned by discovery. Inspect and remove stale private files as needed, and rotate a token if it may have been exposed. diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index 4195576e..90dd8864 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -51,7 +51,8 @@ WebFront is a header-only C++23 HTTP/WebSocket core plus a standalone developer explicitly disabled for development, with the local-process risks described in [Automation](AUTOMATION.md) (#637). Remote access is out of scope and automation does not compile with `WEBFRONT_DISTRIBUTION`. This does not isolate untrusted project code. [Automation](AUTOMATION.md) documents the listener, lifecycle, limits and the supported MCP profile. - The `webfront-agent` launcher, its JSON CLI and MCP on stdio were removed. The pinned environment 1.0.2 describes MCP; + The `webfront-agent` launcher, its JSON CLI and MCP on stdio were removed. The environment 1.0.2 pinned in + [`DeveloperReleaseData.hpp`](../include/webfront/system/DeveloperReleaseData.hpp) describes MCP; the starter guidance for stable client configuration is in the 1.0.3 sources and will reach `wf create` in the next environment release. Until then agents can follow `docs/DEVELOPING_WITH_AGENTS.md`. First-contact guidance for agents (README section, `docs/DEVELOPING_WITH_AGENTS.md`, `webfront_write_agent_guide()`, configuration and diff --git a/docs/adr/ADR-026-configuration-mcp-persistante.md b/docs/adr/ADR-026-configuration-mcp-persistante.md index 39cef934..114dd01e 100644 --- a/docs/adr/ADR-026-configuration-mcp-persistante.md +++ b/docs/adr/ADR-026-configuration-mcp-persistante.md @@ -4,8 +4,8 @@ | Version | Date | État | Auteur | Évolution | Révision Git | | --- | --- | --- | --- | --- | --- | -| 1.0 | 2026-11-22 | Proposée | Ambroise Leclerc | Configuration persistante par projet (#637). | — | -| 1.1 | 2026-11-22 | Acceptée, puis suspendue | Ambroise Leclerc | L'usurpation de l'écouteur révèle une exposition du jeton persistant. | — | +| 1.0 | 2026-11-22 | Proposée | Ambroise Leclerc | Configuration persistante par projet (#637). | 110b138 (historique consigné ; pas de commit distinct) | +| 1.1 | 2026-11-22 | Acceptée, puis suspendue | Ambroise Leclerc | L'usurpation de l'écouteur révèle une exposition du jeton persistant. | 110b138 (historique consigné ; pas de commit distinct) | | 1.2 | 2026-11-22 | Acceptée (livraison en cours) | Ambroise Leclerc | Mode explicite simplifié, compromis de sécurité acceptés ; issue #637 amendée. | #637 | ## Décision @@ -16,7 +16,7 @@ Ces options concernent uniquement le développement : l'automatisation reste exc ## Conséquences -Un autre utilisateur local peut occuper le port pendant l'arrêt de l'application et récupérer un Bearer durable envoyé par le client : ce jeton restera utilisable jusqu'à rotation. Sans authentification, tout processus local pouvant joindre le port peut exercer les grants. Un serveur usurpé peut également renvoyer des réponses mensongères au client. Ces limites sont acceptées uniquement sur choix explicite. Host et Origin protègent contre les requêtes de pages web, pas contre ces processus. Un challenge non standard exigerait un client compatible ; le Bearer fonctionne avec les clients MCP ordinaires. +Un autre utilisateur local peut occuper le port pendant l'arrêt de l'application et récupérer un Bearer durable envoyé par le client : ce jeton restera utilisable jusqu'à rotation. Sans authentification, tout processus local pouvant joindre le port peut exercer les grants. Un serveur usurpé peut également renvoyer des réponses mensongères au client. Ces limites sont acceptées uniquement sur choix explicite. Host et Origin protègent contre les requêtes de pages web, pas contre ces processus. Une authentification par défi-réponse, où le client prouve la possession du secret en répondant à un aléa sans transmettre le secret lui-même, exigerait une prise en charge spécifique du client et n'authentifierait pas à elle seule le serveur ; le Bearer fonctionne avec les clients MCP ordinaires. Après un crash ou un arrêt forcé, le fichier privé de session peut rester sur disque avec le jeton durable. La découverte tente de nettoyer les répertoires de session par défaut lorsque le processus n'existe plus ; ce nettoyage peut être différé ou échouer, et ne touche pas un répertoire fourni explicitement. La fermeture propre retire la configuration. L'application ou son propriétaire doit gérer les fichiers résiduels et la rotation du secret si nécessaire. diff --git a/include/webfront/automation/Enable.hpp b/include/webfront/automation/Enable.hpp index b168451d..d0c67370 100644 --- a/include/webfront/automation/Enable.hpp +++ b/include/webfront/automation/Enable.hpp @@ -127,6 +127,7 @@ class Automation { registration(discoveryDirectory, record(*session, privateDirectory.path, mcp)), grants(std::move(options.grants)), callbackNames(std::move(options.callbacks)), + authenticationDisabled(options.disableMcpAuthentication), grace(options.closeGrace), unresponsive(std::move(options.onUnresponsive)), launched(Clock::now()), @@ -199,7 +200,8 @@ class Automation { std::string names; for (const auto& callback : callbackNames) names += (names.empty() ? "" : ", ") + callback; - const auto granted = "grants: " + (list.empty() ? std::string{"none"} : list) + (names.empty() ? "" : "; callbacks: " + names); + const auto granted = std::string{authenticationDisabled ? "WARNING: MCP authentication disabled; local processes can use granted operations; " : ""} + + "grants: " + (list.empty() ? std::string{"none"} : list) + (names.empty() ? "" : "; callbacks: " + names); return "WebFront MCP (" + granted + "): " + mcp.url() + " - client configuration: " + mcp.configuration().generic_string(); } /// `base` marked as shared with an agent, for a window title: automation must be visible to the person using it. @@ -267,6 +269,7 @@ class Automation { discovery::Registration registration; std::vector grants; std::vector callbackNames; + bool authenticationDisabled; std::chrono::milliseconds grace; std::function unresponsive; std::mutex revocation; diff --git a/include/webfront/automation/McpHttp.hpp b/include/webfront/automation/McpHttp.hpp index 30dae38f..5ec7cf12 100644 --- a/include/webfront/automation/McpHttp.hpp +++ b/include/webfront/automation/McpHttp.hpp @@ -339,14 +339,15 @@ class Endpoint { /// The client configuration of an instance: its URL and its token. `name` names the server for the client. inline std::string clientConfiguration(std::string_view url, std::string_view token, std::string_view name = "webfront", bool authentication = true) { - std::map fields{{"type", json::quote("http")}, {"url", json::quote(url)}}; + std::string server = "{\"type\":" + json::quote("http") + ",\"url\":" + json::quote(url); if (authentication) - fields.emplace("headers", objectJson({{"Authorization", json::quote("Bearer " + std::string(token))}})); - const auto server = objectJson(fields); + server += ",\"headers\":" + objectJson({{"Authorization", json::quote("Bearer " + std::string(token))}}); + server += "}"; return "{\n \"mcpServers\": {\n " + json::quote(name) + ": " + server + "\n }\n}\n"; } -/// Validate the selected authentication options before creating session or listener resources. +/// Validate options at each independent entry point: enableAutomation, direct Automation construction and direct Server +/// construction. The outer checks precede allocation/session creation; Server must also protect its own callers. inline void validateTokenOptions(const std::optional& fixed, bool authentication) { if (!authentication && fixed) throw std::invalid_argument("A fixed MCP token cannot be combined with disabled authentication"); diff --git a/test/unit/AutomationMcpHttpTests.cpp b/test/unit/AutomationMcpHttpTests.cpp index 86157703..f250ef04 100644 --- a/test/unit/AutomationMcpHttpTests.cpp +++ b/test/unit/AutomationMcpHttpTests.cpp @@ -157,6 +157,12 @@ const Scenario mcpHttpScreening{"MCP HTTP requests are screened on their headers require(!mcphttp::screen(parsed(post(port, "{}")), port, token).refusal); const Object defaults{mcphttp::clientConfiguration("http://127.0.0.1:4321/mcp", token)}; require(Object(Object(defaults.raw("mcpServers")).raw("webfront")).has("headers")); + const auto ordered = mcphttp::clientConfiguration("http://127.0.0.1:4321/mcp", token); + require(ordered.find("\"type\"") < ordered.find("\"url\"")); + require(ordered.find("\"url\"") < ordered.find("\"headers\"")); + const Object escaped{mcphttp::clientConfiguration("http://127.0.0.1:4321/mcp", "a\"b", "custom")}; + const Object server{Object(escaped.raw("mcpServers")).raw("custom")}; + require(Object(server.raw("headers")).string("Authorization") == "Bearer a\"b"); require(screened(post(port, "{}", "Expect: 100-continue\r\n")).expectsContinue); }); then("localhost is the other accepted spelling, and the Bearer scheme is case-insensitive", [&] { @@ -626,48 +632,68 @@ const Scenario stableMcp{"A fixed MCP token and port survive activation and auth HttpConsumerApp app{.project = root.path() / "project"}; const auto sessions = root.path() / "sessions"; const std::string fixed(64, 'a'); - auto first = enableAutomation(app, {.mcpToken = fixed, .discovery = sessions, .announce = false}); - const auto port = static_cast(std::stoi(first->mcpUrl().substr(first->mcpUrl().rfind(':') + 1))); - const auto config = channel::readEndpoint(first->directory(), "mcp.json"); - first->close(); - for (int run = 0; run < 2; ++run) { - auto instance = enableAutomation(app, {.mcpPort = port, .mcpToken = fixed, .discovery = sessions, .announce = false}); - require(channel::readEndpoint(instance->directory(), "mcp.json") == config); - for (const auto& entry : discovery::list(sessions)) { - std::ifstream input(sessions / (entry.session + ".json")); - std::ostringstream record; - record << input.rdbuf(); - require(record.str().find(fixed) == std::string::npos); + // A port selected by the OS can be claimed between launches. Retry only that bind error, keeping each + // successful pair on the same port and token; any other failure still fails the scenario. + for (int attempt = 0; ; ++attempt) { + try { + auto first = enableAutomation(app, {.mcpToken = fixed, .discovery = sessions, .announce = false}); + require(first->banner().find("WARNING") == std::string::npos); + const auto port = static_cast(std::stoi(first->mcpUrl().substr(first->mcpUrl().rfind(':') + 1))); + const auto config = channel::readEndpoint(first->directory(), "mcp.json"); + first->close(); + for (int run = 0; run < 2; ++run) { + auto instance = enableAutomation(app, {.mcpPort = port, .mcpToken = fixed, .discovery = sessions, .announce = false}); + require(channel::readEndpoint(instance->directory(), "mcp.json") == config); + for (const auto& entry : discovery::list(sessions)) { + std::ifstream input(sessions / (entry.session + ".json")); + std::ostringstream record; + record << input.rdbuf(); + require(record.str().find(fixed) == std::string::npos); + } + const auto opened = roundTrip(port, post(port, initialize, {}, fixed)); + require(opened.status == 200); + require(roundTrip(port, post(port, initialize, {}, std::string(64, 'b'))).status == 401); + const auto extra = "MCP-Session-Id: " + opened.header("mcp-session-id") + "\r\nMCP-Protocol-Version: 2025-11-25\r\n"; + require(roundTrip(port, post(port, initialized, extra, fixed)).status == 202); + const auto result = roundTrip(port, post(port, R"({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"webfront.session","arguments":{}}})", extra, fixed)); + require(result.status == 200); + require(result.body.find("result") != std::string::npos); + requireThrows([&] { enableAutomation(app, {.mcpPort = port, .mcpToken = fixed, .discovery = sessions, .announce = false}); }); + auto side = enableAutomation(app, {.discovery = sessions, .announce = false}); + require(side->mcpUrl() != instance->mcpUrl()); + side->close(); + instance->close(); + } + auto open = enableAutomation(app, {.mcpPort = port, .disableMcpAuthentication = true, .discovery = sessions, .announce = false}); + require(open->banner().find("WARNING: MCP authentication disabled") != std::string::npos); + require(open->banner().find("local processes can use granted operations") != std::string::npos); + require(open->banner().find("WARNING") < open->banner().find("grants:")); + require(open->banner().ends_with(open->clientConfiguration().generic_string())); + const Object configuration{channel::readEndpoint(open->directory(), "mcp.json")}; + require(!Object(Object(configuration.raw("mcpServers")).raw("webfront")).has("headers")); + require(channel::readEndpoint(open->directory(), "mcp.json").find(fixed) == std::string::npos); + auto request = post(port, initialize); + request.erase(request.find("Authorization:"), request.find("\r\n", request.find("Authorization:")) + 2 - request.find("Authorization:")); + require(roundTrip(port, request).status == 200); + require(roundTrip(port, post(port, initialize, {}, "wrong-token")).status == 200); + require(roundTrip(port, post(port, initialize, "Origin: http://evil.test\r\n")).status == 403); + require(roundTrip(port, post(port, initialize, "Sec-Fetch-Mode: cors\r\n")).status == 403); + require(roundTrip(port, post(port, initialize, "Sec-Fetch-Dest: document\r\n")).status == 403); + auto hostile = request; + hostile.replace(hostile.find("127.0.0.1"), 9, "evil.test"); + require(roundTrip(port, hostile).status == 421); + open->close(); + break; + } catch (const mcphttp::BindError& error) { +#ifdef _WIN32 + const auto addressInUse = WSAEADDRINUSE; +#else + const auto addressInUse = EADDRINUSE; +#endif + if (error.code().value() != addressInUse || attempt == 4) + throw; } - const auto opened = roundTrip(port, post(port, initialize, {}, fixed)); - require(opened.status == 200); - require(roundTrip(port, post(port, initialize, {}, std::string(64, 'b'))).status == 401); - const auto extra = "MCP-Session-Id: " + opened.header("mcp-session-id") + "\r\nMCP-Protocol-Version: 2025-11-25\r\n"; - require(roundTrip(port, post(port, initialized, extra, fixed)).status == 202); - const auto result = roundTrip(port, post(port, R"({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"webfront.session","arguments":{}}})", extra, fixed)); - require(result.status == 200); - require(result.body.find("result") != std::string::npos); - requireThrows([&] { enableAutomation(app, {.mcpPort = port, .mcpToken = fixed, .discovery = sessions, .announce = false}); }); - auto side = enableAutomation(app, {.discovery = sessions, .announce = false}); - require(side->mcpUrl() != instance->mcpUrl()); - side->close(); - instance->close(); } - auto open = enableAutomation(app, {.mcpPort = port, .disableMcpAuthentication = true, .discovery = sessions, .announce = false}); - const Object configuration{channel::readEndpoint(open->directory(), "mcp.json")}; - require(!Object(Object(configuration.raw("mcpServers")).raw("webfront")).has("headers")); - require(channel::readEndpoint(open->directory(), "mcp.json").find(fixed) == std::string::npos); - auto request = post(port, initialize); - request.erase(request.find("Authorization:"), request.find("\r\n", request.find("Authorization:")) + 2 - request.find("Authorization:")); - require(roundTrip(port, request).status == 200); - require(roundTrip(port, post(port, initialize, {}, "wrong-token")).status == 200); - require(roundTrip(port, post(port, initialize, "Origin: http://evil.test\r\n")).status == 403); - require(roundTrip(port, post(port, initialize, "Sec-Fetch-Mode: cors\r\n")).status == 403); - require(roundTrip(port, post(port, initialize, "Sec-Fetch-Dest: document\r\n")).status == 403); - auto hostile = request; - hostile.replace(hostile.find("127.0.0.1"), 9, "evil.test"); - require(roundTrip(port, hostile).status == 421); - open->close(); requireThrows([&] { enableAutomation(app, {.mcpToken = "", .discovery = sessions, .announce = false}); }); requireThrows([&] { enableAutomation(app, {.mcpToken = "a", .discovery = sessions, .announce = false}); }); requireThrows([&] { enableAutomation(app, {.mcpToken = std::string(31, 'a'), .discovery = sessions, .announce = false}); }); @@ -686,3 +712,19 @@ const Scenario stableMcp{"A fixed MCP token and port survive activation and auth auto minimum = enableAutomation(app, {.mcpToken = std::string(32, 'a'), .discovery = sessions, .announce = false}); minimum->close(); }}; + +const Scenario unauthenticatedMcpBanner{"An unauthenticated MCP listener warns at startup", [] { + using namespace mcphttptests; + webfront::test::TemporaryDirectory root; + std::filesystem::create_directory(root.path() / "project"); + HttpConsumerApp app{.project = root.path() / "project"}; + std::ostringstream captured; + struct RestoreBuffer { + std::streambuf* previous; + ~RestoreBuffer() { std::cerr.rdbuf(previous); } + } restore{std::cerr.rdbuf(captured.rdbuf())}; + auto automation = enableAutomation(app, {.disableMcpAuthentication = true, .discovery = root.path() / "sessions"}); + require(captured.str().find("WARNING: MCP authentication disabled") != std::string::npos); + require(captured.str().find(automation->mcpUrl()) != std::string::npos); + automation->close(); +}}; From c30b41bb2479160ca8f6f5703e8749a17ac2509a Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:15:45 +0100 Subject: [PATCH 08/10] Harden MCP test retry and qualify token comparison --- docs/AUTOMATION.md | 5 +-- .../ADR-025-mcp-http-dans-l-application.md | 5 +-- .../ADR-026-configuration-mcp-persistante.md | 6 ++-- include/webfront/automation/Credentials.hpp | 1 + test/tools/AutomationClient.py | 12 ++++++- test/tools/AutomationClientTest.py | 32 +++++++++++++++++++ test/web/CMakeLists.txt | 2 ++ 7 files changed, 55 insertions(+), 8 deletions(-) create mode 100644 test/tools/AutomationClientTest.py diff --git a/docs/AUTOMATION.md b/docs/AUTOMATION.md index c5f0f80a..3fde206b 100644 --- a/docs/AUTOMATION.md +++ b/docs/AUTOMATION.md @@ -136,8 +136,9 @@ operation of `webfront.start`, not one MCP tool per callback, so the tool list s served with TLS, whatever the application's own address and TLS listener. `mcpPort` chooses a port; a chosen port is never replaced: when it is taken the activation throws a `std::system_error` that names the address, the port and the cause. Each instance has its own URL, so several applications run side by side and the agent picks one by its URL. -- **Token.** Every request carries `Authorization: Bearer `, a 256-bit value from the OS, compared in constant time - before the body is parsed; otherwise 401 with `WWW-Authenticate: Bearer` (no OAuth server is announced). The token lives as +- **Token.** By default every request carries `Authorization: Bearer `, a 256-bit value from the OS. Before parsing the + body, the listener compares equal-length tokens in constant time and rejects a length mismatch immediately; a failed check gets + 401 with `WWW-Authenticate: Bearer` (no OAuth server is announced). The token lives as long as the session by default: closing it, a deadline or a lost window closes the listener and removes the file. A supplied `mcpToken` remains valid across launches until the application changes it; authentication can be explicitly disabled. - **Client configuration.** `mcp.json` (mode 0600 in a 0700 directory on POSIX, owner-only ACL on Windows) holds the URL and diff --git a/docs/adr/ADR-025-mcp-http-dans-l-application.md b/docs/adr/ADR-025-mcp-http-dans-l-application.md index 18433a17..6c9bcf56 100644 --- a/docs/adr/ADR-025-mcp-http-dans-l-application.md +++ b/docs/adr/ADR-025-mcp-http-dans-l-application.md @@ -78,7 +78,8 @@ Le port est celui que l'OS attribue (`0`), selon le mécanisme de #617 ; une opt Chaque activation tire un jeton de 256 bits de l'aléa de l'OS, distinct de la capacité du canal JSON-lines, du secret de lancement de la page et de l'identifiant de session. Chaque requête porte `Authorization: Bearer ` ; la comparaison -est à temps constant et précède la lecture du JSON. Sinon : 401 avec `WWW-Authenticate: Bearer`, sans `resource_metadata`, +parcourt tout le jeton à temps constant lorsque les longueurs sont égales. Une différence de longueur est rejetée immédiatement. +La comparaison précède la lecture du JSON. Sinon : 401 avec `WWW-Authenticate: Bearer`, sans `resource_metadata`, car aucun serveur d'autorisation OAuth n'est annoncé. Le jeton vit autant que la session : il est révoqué à sa fermeture (fermeture normale, échéance native, fenêtre perdue, watchdog, signal que l'application intercepte pour fermer), l'écouteur est alors fermé, et une nouvelle activation tire un nouveau jeton. Pas de rotation pendant la session. @@ -203,7 +204,7 @@ Les menaces, actifs et risques résiduels de l'ADR-019 restent valables. Ce qui | Menace et gravité | Mesures | Risque résiduel | | --- | --- | --- | | Rebinding DNS, page web qui vise le port MCP — critique | Écouteur loopback distinct ; Host exact ; tout `Origin` et tout `Sec-Fetch-*` refusés ; `application/json` exigé ; aucun CORS ; jeton exigé en plus. | Un navigateur qui omettrait `Origin` sur un `POST` cross-origin et ignorerait la pré-vérification resterait sans jeton. | -| Client local non autorisé — critique | Jeton de 256 bits, comparaison à temps constant, avant tout traitement ; fichier privé hors projet. | Un processus du même utilisateur peut lire `mcp.json`, comme il lisait le fichier du canal JSON-lines. | +| Client local non autorisé — critique | Jeton de 256 bits, comparaison à temps constant à longueur égale, avant tout traitement ; fichier privé hors projet. | La longueur est observable ; un processus du même utilisateur peut lire `mcp.json`, comme il lisait le fichier du canal JSON-lines. | | Fuite du jeton — élevée | Jamais dans le projet, la page, l'URL, la ligne de commande, les journaux, l'affichage ou l'enregistrement ; vie limitée à la session. | Une personne qui copie le fichier dans le projet ou un dépôt l'expose ; la documentation l'interdit, aucun contrôle ne l'empêche. | | Exposition réseau — critique | Liaison 127.0.0.1 seule, indépendante de l'adresse et du TLS de l'application ; adresse non configurable. | Un transfert de port établi par l'utilisateur étend l'accès hors de cette décision. | | Automatisation expédiée — critique | Erreur de compilation sous `WEBFRONT_DISTRIBUTION`. | Une build qui ne définit pas cette macro n'est pas protégée par elle. | diff --git a/docs/adr/ADR-026-configuration-mcp-persistante.md b/docs/adr/ADR-026-configuration-mcp-persistante.md index 114dd01e..91f2ed5d 100644 --- a/docs/adr/ADR-026-configuration-mcp-persistante.md +++ b/docs/adr/ADR-026-configuration-mcp-persistante.md @@ -4,15 +4,15 @@ | Version | Date | État | Auteur | Évolution | Révision Git | | --- | --- | --- | --- | --- | --- | -| 1.0 | 2026-11-22 | Proposée | Ambroise Leclerc | Configuration persistante par projet (#637). | 110b138 (historique consigné ; pas de commit distinct) | -| 1.1 | 2026-11-22 | Acceptée, puis suspendue | Ambroise Leclerc | L'usurpation de l'écouteur révèle une exposition du jeton persistant. | 110b138 (historique consigné ; pas de commit distinct) | +| 1.0 | 2026-11-22 | Proposée | Ambroise Leclerc | Configuration persistante par projet (#637). | [110b138](https://github.com/ambroise-leclerc/WebFront/commit/110b138301a4920e0a25d6614644624602943cc3) (historique consigné ; pas de commit distinct) | +| 1.1 | 2026-11-22 | Acceptée, puis suspendue | Ambroise Leclerc | L'usurpation de l'écouteur révèle une exposition du jeton persistant. | [110b138](https://github.com/ambroise-leclerc/WebFront/commit/110b138301a4920e0a25d6614644624602943cc3) (historique consigné ; pas de commit distinct) | | 1.2 | 2026-11-22 | Acceptée (livraison en cours) | Ambroise Leclerc | Mode explicite simplifié, compromis de sécurité acceptés ; issue #637 amendée. | #637 | ## Décision Le mode de l'ADR-025 reste le défaut : port choisi par l'OS, jeton aléatoire par session et configuration privée supprimée à la fermeture. L'application peut fixer le port et fournir un jeton Bearer durable, ou désactiver explicitement l'authentification. Le développeur gère le secret et sa rotation ; WebFront ne le persiste pas hors de la configuration privée de session. Le client copie une fois URL et en-tête dans sa configuration utilisateur, hors projet. Il doit lancer l'application avant de se connecter. Un port occupé provoque une erreur explicite ; une autre instance peut utiliser le mode par défaut. La découverte ne contient pas de jeton. -Ces options concernent uniquement le développement : l'automatisation reste exclue des builds de distribution. L'écoute reste sur loopback ; Host, Origin et Sec-Fetch-* restent vérifiés. Un jeton configuré est comparé en temps constant. Les valeurs malformées et les combinaisons ambiguës sont refusées. +Ces options concernent uniquement le développement : l'automatisation reste exclue des builds de distribution. L'écoute reste sur loopback ; Host, Origin et Sec-Fetch-* restent vérifiés. La comparaison d'un jeton configuré parcourt tous ses caractères à temps constant lorsque les longueurs sont égales ; elle rejette immédiatement une différence de longueur. Les valeurs malformées et les combinaisons ambiguës sont refusées. ## Conséquences diff --git a/include/webfront/automation/Credentials.hpp b/include/webfront/automation/Credentials.hpp index 506c8c44..a8780575 100644 --- a/include/webfront/automation/Credentials.hpp +++ b/include/webfront/automation/Credentials.hpp @@ -25,6 +25,7 @@ inline std::string nonce() { } return result; } +/// Content comparison is constant-time for equal lengths; a length mismatch is rejected immediately. inline bool sameToken(std::string_view left, std::string_view right) { if (left.size() != right.size()) return false; diff --git a/test/tools/AutomationClient.py b/test/tools/AutomationClient.py index 04e01fbb..661554a3 100644 --- a/test/tools/AutomationClient.py +++ b/test/tools/AutomationClient.py @@ -563,6 +563,14 @@ def session(args): print("MCP real-window regression passed: diagnostics/correction/check/build/test/preview/actions/cancellation/shared session/setup") +def port_conflict_after_failure(process, timeout=1): + """Wait briefly for the host's collision status after discovery fails; other failures are not retried.""" + try: + return process.wait(timeout=timeout) == 73 + except subprocess.TimeoutExpired: + return False + + def stable(args): pathlib.Path(args.work).mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(dir=args.work, prefix="stable-") as temporary: @@ -593,7 +601,9 @@ def stable(args): try: path = pathlib.Path(host.record()["configuration"]) except AssertionError: - if host.process.poll() == 73: + # Allow a just-exiting host to publish its status; a still-running host or any other + # exit code retains the original failure rather than being treated as a collision. + if port_conflict_after_failure(host.process): # On either launch the port may have been taken in the gap; restart both launches # with a new port and client so each successful pair still uses one configuration. break diff --git a/test/tools/AutomationClientTest.py b/test/tools/AutomationClientTest.py new file mode 100644 index 00000000..0da1a17f --- /dev/null +++ b/test/tools/AutomationClientTest.py @@ -0,0 +1,32 @@ +"""Port-collision status can arrive just after discovery fails.""" +import subprocess +import sys +import unittest + +import AutomationClient + + +class PortConflictRetry(unittest.TestCase): + def test_waits_for_late_collision_exit(self): + with subprocess.Popen([sys.executable, "-c", "import sys; sys.stdin.read(1); raise SystemExit(73)"], stdin=subprocess.PIPE) as process: + self.assertIsNone(process.poll()) + process.stdin.write(b"x") + process.stdin.flush() + self.assertTrue(AutomationClient.port_conflict_after_failure(process, timeout=5)) + self.assertEqual(process.returncode, 73) + + def test_other_exit_is_not_retried(self): + with subprocess.Popen([sys.executable, "-c", "raise SystemExit(1)"]) as process: + self.assertFalse(AutomationClient.port_conflict_after_failure(process, timeout=5)) + self.assertEqual(process.returncode, 1) + + def test_still_running_is_not_retried(self): + with subprocess.Popen([sys.executable, "-c", "import time; time.sleep(10)"]) as process: + try: + self.assertFalse(AutomationClient.port_conflict_after_failure(process, timeout=0.05)) + finally: + process.terminate() + + +if __name__ == "__main__": + unittest.main() diff --git a/test/web/CMakeLists.txt b/test/web/CMakeLists.txt index 6761391d..b655c5d1 100644 --- a/test/web/CMakeLists.txt +++ b/test/web/CMakeLists.txt @@ -163,6 +163,8 @@ if(_browser_tests_available) # The cleanup of a browser profile that a helper still writes into after the application exited (#642). add_test(NAME AutomationProfileCleanup COMMAND "${Python3_EXECUTABLE}" "${PROJECT_SOURCE_DIR}/test/tools/ProfileCleanupTest.py") set_tests_properties(AutomationProfileCleanup PROPERTIES LABELS fast TIMEOUT 30) + add_test(NAME AutomationClientRetry COMMAND "${Python3_EXECUTABLE}" "${PROJECT_SOURCE_DIR}/test/tools/AutomationClientTest.py") + set_tests_properties(AutomationClientRetry PROPERTIES LABELS fast TIMEOUT 30) endif() if(Python3_Interpreter_FOUND AND _automation_windows_available) # An application that enabled automation, which serves MCP itself (ADR-025): the program every scenario drives From 65aa02494b23fa48cc66070ef0291a26f7698250 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:56:40 +0100 Subject: [PATCH 09/10] Address review remarks on the stable MCP configuration (#637) --- docs/AUTOMATION.md | 2 +- docs/DEVELOPER_ENVIRONMENT.md | 5 +++-- docs/adr/ADR-026-configuration-mcp-persistante.md | 2 +- test/tools/AutomationClient.py | 2 ++ 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/AUTOMATION.md b/docs/AUTOMATION.md index 3fde206b..12fc9ad7 100644 --- a/docs/AUTOMATION.md +++ b/docs/AUTOMATION.md @@ -71,7 +71,7 @@ auto automation = webfront::automation::enableAutomation( app, {.grants = {"check", "build"}, .mcpPort = 19002, .mcpToken = std::string{token}}); ``` -The application includes ``, `` and `` for this example. A configured token must be 32–1024 visible ASCII characters without spaces; length alone does not guarantee randomness. To opt in to an unauthenticated listener instead, use `.disableMcpAuthentication = true` and omit `mcpToken`; its client configuration has no Authorization header. In that mode any Authorization header, including an incorrect Bearer, is ignored. +The application includes ``, `` and `` for this example; MSVC reports `std::getenv` as deprecated (C4996), so use `_dupenv_s` or define `_CRT_SECURE_NO_WARNINGS` there. A configured token must be 32–1024 visible ASCII characters without spaces; length alone does not guarantee randomness. To opt in to an unauthenticated listener instead, use `.disableMcpAuthentication = true` and omit `mcpToken`; its client configuration has no Authorization header. In that mode any Authorization header, including an incorrect Bearer, is ignored. The startup banner warns when authentication is disabled. It appears in the developer terminal and on stderr; as with the normal banner, `announce = false` suppresses the stderr copy. diff --git a/docs/DEVELOPER_ENVIRONMENT.md b/docs/DEVELOPER_ENVIRONMENT.md index 0e908183..b3b9c09b 100644 --- a/docs/DEVELOPER_ENVIRONMENT.md +++ b/docs/DEVELOPER_ENVIRONMENT.md @@ -794,8 +794,9 @@ GitHub Pages downloads; no npm publication or scope ownership is required. The version in `distribution.json` is the version built from the current sources (currently 1.0.3, not yet published). It can be ahead of `DeveloperReleaseData.hpp`, which pins the published 1.0.2 environment used by applications. The -compatibility table above records that published pin, not the next source build. The pin changes only when a new -distribution is published and adopted. +compatibility table above records that published pin, not the next source build. The default branch receives a new +pin only after the new distribution is published and its files are verified. Before the tag, the release branch carries +the regenerated header, and `wf run build --refresh-bootstrap` rewrites it locally. The `SelfBuild*` CTest cases run the scripts on a copy of the sources, with the dependencies installed from the local registry: the build, a repeat build (same bytes), the checked-in bootstrap bundles and checksums rebuilt by wf alone (and the diff --git a/docs/adr/ADR-026-configuration-mcp-persistante.md b/docs/adr/ADR-026-configuration-mcp-persistante.md index 91f2ed5d..f30ab18b 100644 --- a/docs/adr/ADR-026-configuration-mcp-persistante.md +++ b/docs/adr/ADR-026-configuration-mcp-persistante.md @@ -22,4 +22,4 @@ Après un crash ou un arrêt forcé, le fichier privé de session peut rester su ## Validation -Relancer l'application deux fois avec la même configuration cliente et appeler initialize puis webfront.session, avec le client HTTP du dépôt et le SDK 2.3.0 s'il est disponible. Vérifier les refus, les instances concurrentes, le conflit de port, l'absence de secret dans la découverte et les protections réseau dans les modes authentifié et sans authentification. Maintenir les guides et AgentGuidance. +Relancer l'application deux fois avec la même configuration cliente et appeler initialize puis webfront.session, avec le client HTTP du dépôt et le SDK 2.3.0 s'il est disponible. Vérifier les refus, les instances concurrentes, le conflit de port, l'absence de secret dans la découverte et les protections réseau dans les modes authentifié et sans authentification. Maintenir les guides et AgentGuidance. À la fusion, passer l'état à « Acceptée » et consigner les révisions Git réelles dans l'historique. diff --git a/test/tools/AutomationClient.py b/test/tools/AutomationClient.py index 661554a3..0fc37168 100644 --- a/test/tools/AutomationClient.py +++ b/test/tools/AutomationClient.py @@ -622,6 +622,8 @@ def stable(args): finally: host.close() else: + # No break: both launches succeeded on this port, so the scenario is done. A break (port taken + # in the gap) skips this and retries both launches with a new port. return raise AssertionError("MCP port was occupied on all five attempts") From f7b1ad73188df33703b1a70068a4035ad90e647b Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Mon, 23 Nov 2026 08:41:27 +0100 Subject: [PATCH 10/10] Centralize MCP address-in-use detection --- docs/AUTOMATION.md | 2 +- include/webfront/automation/McpHttp.hpp | 8 ++++++++ test/unit/AutomationMcpHttpTests.cpp | 24 ++++++++++++++++++------ test/web/AutomationHost.cpp | 7 +------ 4 files changed, 28 insertions(+), 13 deletions(-) diff --git a/docs/AUTOMATION.md b/docs/AUTOMATION.md index 12fc9ad7..1b2fae73 100644 --- a/docs/AUTOMATION.md +++ b/docs/AUTOMATION.md @@ -73,7 +73,7 @@ auto automation = webfront::automation::enableAutomation( The application includes ``, `` and `` for this example; MSVC reports `std::getenv` as deprecated (C4996), so use `_dupenv_s` or define `_CRT_SECURE_NO_WARNINGS` there. A configured token must be 32–1024 visible ASCII characters without spaces; length alone does not guarantee randomness. To opt in to an unauthenticated listener instead, use `.disableMcpAuthentication = true` and omit `mcpToken`; its client configuration has no Authorization header. In that mode any Authorization header, including an incorrect Bearer, is ignored. -The startup banner warns when authentication is disabled. It appears in the developer terminal and on stderr; as with the normal banner, `announce = false` suppresses the stderr copy. +The startup banner warns when authentication is disabled. It appears on stderr and, once the window connects, in the developer terminal. With `announce = false` there is no stderr warning; the terminal still receives the banner when it connects, and `automation->banner()` still returns it. These options are for trusted development environments. A different local user can occupy the fixed port while the application is stopped and receive a durable Bearer sent by the client, then reuse it when the application starts. Without authentication, any local process that reaches the listener can exercise its grants. A fake server can also send misleading responses. Loopback, strict Host, Origin and Sec-Fetch checks remain enabled in both modes; they do not authenticate the server to the client. diff --git a/include/webfront/automation/McpHttp.hpp b/include/webfront/automation/McpHttp.hpp index 5ec7cf12..3ceded13 100644 --- a/include/webfront/automation/McpHttp.hpp +++ b/include/webfront/automation/McpHttp.hpp @@ -360,6 +360,14 @@ class BindError : public std::system_error { public: BindError(std::error_code cause, unsigned short port) : std::system_error(cause, "WebFront cannot listen for MCP on 127.0.0.1:" + std::to_string(port)) { } + /// Whether the native error reports that the requested port is already in use. + [[nodiscard]] bool addressInUse() const noexcept { +#ifdef _WIN32 + return code().value() == WSAEADDRINUSE; +#else + return code().value() == EADDRINUSE; +#endif + } }; /// The loopback listener. It writes `mcp.json` into `directory` (an existing private directory outside the project) and diff --git a/test/unit/AutomationMcpHttpTests.cpp b/test/unit/AutomationMcpHttpTests.cpp index f250ef04..c30d2cd9 100644 --- a/test/unit/AutomationMcpHttpTests.cpp +++ b/test/unit/AutomationMcpHttpTests.cpp @@ -685,12 +685,7 @@ const Scenario stableMcp{"A fixed MCP token and port survive activation and auth open->close(); break; } catch (const mcphttp::BindError& error) { -#ifdef _WIN32 - const auto addressInUse = WSAEADDRINUSE; -#else - const auto addressInUse = EADDRINUSE; -#endif - if (error.code().value() != addressInUse || attempt == 4) + if (!error.addressInUse() || attempt == 4) throw; } } @@ -727,4 +722,21 @@ const Scenario unauthenticatedMcpBanner{"An unauthenticated MCP listener warns a require(captured.str().find("WARNING: MCP authentication disabled") != std::string::npos); require(captured.str().find(automation->mcpUrl()) != std::string::npos); automation->close(); + captured.str(""); + captured.clear(); + auto silent = enableAutomation(app, {.disableMcpAuthentication = true, .discovery = root.path() / "sessions", .announce = false}); + require(captured.str().empty()); + require(silent->banner().find("WARNING: MCP authentication disabled") != std::string::npos); + silent->close(); +}}; + +const Scenario mcpBindError{"MCP bind errors identify an occupied address", [] { + using namespace mcphttptests; +#ifdef _WIN32 + const int occupied = WSAEADDRINUSE; +#else + const int occupied = EADDRINUSE; +#endif + require(mcphttp::BindError{std::error_code{occupied, std::system_category()}, 1234}.addressInUse()); + require(!mcphttp::BindError{std::make_error_code(std::errc::permission_denied), 1234}.addressInUse()); }}; diff --git a/test/web/AutomationHost.cpp b/test/web/AutomationHost.cpp index 697668f4..3cfc89b0 100644 --- a/test/web/AutomationHost.cpp +++ b/test/web/AutomationHost.cpp @@ -183,12 +183,7 @@ int main(int argc, char** argv) { return status; } catch (const webfront::automation::mcphttp::BindError& error) { std::cerr << "automation_host: " << error.what() << '\n'; -#ifdef _WIN32 - const auto addressInUse = WSAEADDRINUSE; -#else - const auto addressInUse = EADDRINUSE; -#endif - if (error.code().value() == addressInUse) + if (error.addressInUse()) return 73; return 1; } catch (const std::exception& error) {