From ddc77a8ec5e80e2b55ca6f04d699efe91c3db1a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:12:21 +0300 Subject: [PATCH 01/26] test: bring stale tests in line with current behaviour MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The install route takes source_id + scope, the PR chip spells out its state, and onboarding's Continue is always enabled; the tests still expected the old behaviour. phase4_apis now also runs against a temporary FLEETIFY_HOME. Two tests raced: the python_runtime env tests now hold the crate's env lock, and the loopback child test no longer serves on the port its parent released for the unreachable proxy. Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- .../src/services/python_runtime.rs | 6 ++++ crates/fleetify-backend/tests/phase4_apis.rs | 29 ++++++++++++++----- crates/fleetify-core/src/loopback.rs | 14 ++++++++- .../git/__tests__/pr-switcher-chip.test.tsx | 22 +++++++------- .../__tests__/install-provider-id.test.ts | 16 +++++----- src/components/onboarding/onboarding-chat.tsx | 7 ++--- 6 files changed, 64 insertions(+), 30 deletions(-) diff --git a/crates/fleetify-backend/src/services/python_runtime.rs b/crates/fleetify-backend/src/services/python_runtime.rs index 889bbff..3a4e6d7 100644 --- a/crates/fleetify-backend/src/services/python_runtime.rs +++ b/crates/fleetify-backend/src/services/python_runtime.rs @@ -149,6 +149,9 @@ mod tests { #[test] fn override_env_wins_when_set_and_exists() { + let _g = crate::test_support::home_lock() + .lock() + .unwrap_or_else(|p| p.into_inner()); // The dev/CI box has *some* path that exists; use the test binary // itself as a stand-in for a Python the user pinned via env. The // function only checks `.exists()`, not whether it's actually a @@ -162,6 +165,9 @@ mod tests { #[test] fn override_env_ignored_when_path_missing() { + let _g = crate::test_support::home_lock() + .lock() + .unwrap_or_else(|p| p.into_inner()); std::env::set_var( "FLEETIFY_EMBEDDED_PYTHON", "/definitely/not/a/real/path/python", diff --git a/crates/fleetify-backend/tests/phase4_apis.rs b/crates/fleetify-backend/tests/phase4_apis.rs index 24fb523..e50d27a 100644 --- a/crates/fleetify-backend/tests/phase4_apis.rs +++ b/crates/fleetify-backend/tests/phase4_apis.rs @@ -50,6 +50,10 @@ async fn phase4_apis_smoke() { }); std::env::set_var("FLEETIFY_ISSUER", format!("http://{jwks_addr}")); std::env::set_var("FLEET_DB_URL", "sqlite::memory:"); + // Plugins and workflows are read from FLEETIFY_HOME: an empty temp dir + // keeps the test off the developer's real ~/.fleetify. + let fleetify_home = tempfile::tempdir().unwrap(); + std::env::set_var("FLEETIFY_HOME", fleetify_home.path()); // 3. Mint a JWT for user "u". let mut header = Header::new(jsonwebtoken::Algorithm::RS256); @@ -163,7 +167,8 @@ async fn phase4_apis_smoke() { .unwrap(); assert_eq!(r.status(), 200); - // ── /api/plugins/install requires repo_url ── + // ── /api/plugins/install addresses a plugin by source_id + scope ── + // The old `{repo_url}` body no longer deserializes. let r = client .post(format!("{base}/api/plugins/install")) .header("Authorization", &auth) @@ -171,13 +176,21 @@ async fn phase4_apis_smoke() { .send() .await .unwrap(); - assert_eq!(r.status(), 200); - let v: serde_json::Value = r.json().await.unwrap(); - assert_eq!(v["ok"], false); - assert!(v["error"] - .as_str() - .unwrap() - .contains("repo_url is required")); + assert_eq!(r.status(), 422); + + // A source the caller has no row for (the one deleted above) is a 404. + let r = client + .post(format!("{base}/api/plugins/install")) + .header("Authorization", &auth) + .json(&serde_json::json!({ + "source_id": source_id, + "scope": { "scope_type": "user" } + })) + .send() + .await + .unwrap(); + assert_eq!(r.status(), 404); + assert!(r.text().await.unwrap().contains("not found")); // ── /api/workflows lists 0 (no plugins installed in test home) ── let r = client diff --git a/crates/fleetify-core/src/loopback.rs b/crates/fleetify-core/src/loopback.rs index 953863e..c58532c 100644 --- a/crates/fleetify-core/src/loopback.rs +++ b/crates/fleetify-core/src/loopback.rs @@ -88,7 +88,19 @@ mod tests { .build() .unwrap(); runtime.block_on(async { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + // The parent picked the proxy's port by binding it and letting it + // go, so the OS may hand that same port to this server. A second + // bind made while the first listener still holds it gets another. + let proxy = std::env::var("HTTP_PROXY").unwrap(); + let proxy_port = reqwest::Url::parse(&proxy).unwrap().port().unwrap(); + let first = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let listener = if first.local_addr().unwrap().port() == proxy_port { + let second = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + drop(first); + second + } else { + first + }; let url = format!("http://127.0.0.1:{}/", listener.local_addr().unwrap().port()); tokio::spawn(async move { while let Ok((mut socket, _)) = listener.accept().await { diff --git a/src/components/git/__tests__/pr-switcher-chip.test.tsx b/src/components/git/__tests__/pr-switcher-chip.test.tsx index 53f5b07..e2ef9ca 100644 --- a/src/components/git/__tests__/pr-switcher-chip.test.tsx +++ b/src/components/git/__tests__/pr-switcher-chip.test.tsx @@ -39,14 +39,16 @@ describe("prIconColor draft handling", () => { }); }); -describe("PrSwitcherChip dot", () => { - const dotOf = (container: HTMLElement) => { - // The status dot is the chip button's first span (6×6 rounded). - const dot = container.querySelector("button span") as HTMLElement; - return dot.style.background; +describe("PrSwitcherChip state label", () => { + const stateOf = (container: HTMLElement) => { + // The state word ("Open", "Draft", …) is the chip button's last span, + // coloured by state. + const spans = container.querySelectorAll("button span"); + const label = spans[spans.length - 1] as HTMLElement; + return { word: label.textContent, color: label.style.color }; }; - it("renders a gray dot for a selected draft PR", () => { + it("labels a selected draft PR 'Draft' in gray", () => { const { container } = render( { onOpenUrl={vi.fn()} />, ); - expect(dotOf(container)).toBe("var(--c-dim)"); + expect(stateOf(container)).toEqual({ word: "Draft", color: "var(--c-dim)" }); }); - it("renders a green dot for an active (non-draft) PR", () => { + it("labels an active (non-draft) PR 'Open' in green", () => { const { container } = render( { />, ); // The DOM style engine normalizes rgb() with spaces after commas. - expect(dotOf(container)).toBe("rgb(64, 180, 120)"); + expect(stateOf(container)).toEqual({ word: "Open", color: "rgb(64, 180, 120)" }); }); it("falls back to the prList entry's draft flag before the detail poll lands", () => { @@ -83,6 +85,6 @@ describe("PrSwitcherChip dot", () => { onOpenUrl={vi.fn()} />, ); - expect(dotOf(container)).toBe("var(--c-dim)"); + expect(stateOf(container)).toEqual({ word: "Draft", color: "var(--c-dim)" }); }); }); diff --git a/src/components/onboarding/__tests__/install-provider-id.test.ts b/src/components/onboarding/__tests__/install-provider-id.test.ts index fd9ddd7..091f9cd 100644 --- a/src/components/onboarding/__tests__/install-provider-id.test.ts +++ b/src/components/onboarding/__tests__/install-provider-id.test.ts @@ -126,15 +126,15 @@ describe("OnboardingChat install IPC", () => { expect(ids.length).toBe(catalog.length + studioProviders.length); }); - it("renders a Continue button gated on at least one ready provider", () => { + it("renders an always-enabled Continue button (no provider is mandatory)", () => { // The main-agent picker used to appear automatically after a // fixed timer; users complained it fired before they finished // pasting keys. The widget now exposes onContinue and renders - // a ContinueRow at the bottom, enabled only when isProviderReady - // returns true for at least one row. + // a ContinueRow at the bottom. It is always enabled: the user can + // finish provider setup later from Settings → Providers. expect(onboardingSrc).toMatch(/\s*isProviderReady\b/); + expect(onboardingSrc).toMatch(/ { @@ -179,9 +179,11 @@ describe("OnboardingChat install IPC", () => { // DeepSeek / Grok / Kimi API / Perplexity / NVIDIA NIM don't have // env-var buckets on the scan probe — falling through to the // empty-label branch left them with a bare dot in the picker - // while OpenAI / Google AI still said "Add key". Mirror those - // by adding a `p.kind === "api"` fallback in getInstallInfo. - expect(onboardingSrc).toMatch(/p\.kind\s*===\s*"api"[\s\S]{0,200}label:\s*"Add key"/); + // while OpenAI / Google AI still said "Add key". The picker now + // groups every `p.kind === "api"` provider into its "API" section, + // whose action is "Add key". + expect(onboardingSrc).toMatch(/const apiKind\s*=\s*phaseProviders\.filter\(\(p\)\s*=>\s*p\.kind\s*===\s*"api"\)/); + expect(onboardingSrc).toMatch(/title:\s*"API",\s*list:\s*apiKind,[\s\S]{0,80}label:\s*"Add key"/); }); it("KeyEntryRow supports a saved mode with masked preview and Edit", () => { diff --git a/src/components/onboarding/onboarding-chat.tsx b/src/components/onboarding/onboarding-chat.tsx index 28950ec..57f74ef 100644 --- a/src/components/onboarding/onboarding-chat.tsx +++ b/src/components/onboarding/onboarding-chat.tsx @@ -2180,10 +2180,9 @@ function ScanWidget({ ); } -/** Continue affordance at the bottom of the verify list. Disabled - * until at least one provider in the list is fully ready — gating - * the parent's main-agent picker / readout cascade on something the - * user can actually drive a chat with. */ +/** Continue affordance at the bottom of the verify list. The list + * always renders it enabled: no provider is mandatory, and the user + * can finish setup later from Settings → Providers. */ function ContinueRow({ enabled, onContinue, From 6c08e888a1589c895fc3fd8d3fdf7ae7002ad50f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:16:46 +0300 Subject: [PATCH 02/26] test: give main-agent-models its full api mock MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- src/components/onboarding/__tests__/main-agent-models.test.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/components/onboarding/__tests__/main-agent-models.test.tsx b/src/components/onboarding/__tests__/main-agent-models.test.tsx index c4cf2f2..75494c4 100644 --- a/src/components/onboarding/__tests__/main-agent-models.test.tsx +++ b/src/components/onboarding/__tests__/main-agent-models.test.tsx @@ -14,6 +14,8 @@ import type { ProviderTile } from "@/lib/providers-api"; vi.mock("@/lib/api", () => ({ fetchAgentModels: vi.fn(async () => ({ models: [], current: null })), fetchProviderModels: vi.fn(async () => []), + // discoverLive probes the catalog first; "unchanged" skips the model heal. + revalidateCatalog: vi.fn(async () => ({ changed: false, probed: false, commit: null, tag: null })), // OnboardingChat (pulled in transitively) imports these; never called here. apiScanProviders: vi.fn(async () => null), checkPythonRuntime: vi.fn(async () => null), From 8436bd730988c6593910152c7daf2f7737524e64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:48:17 +0300 Subject: [PATCH 03/26] fix(backend): answer only requests addressed to the app's own host MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The embedded backend now checks the Host header on every request, the UI files, /healthz and unmatched paths included. It answers only 127.0.0.1: and localhost:; any other host, or none, gets a plain-text 403. The check is the router's outermost layer. The CORS layer is gone. The app's pages share the backend's origin, or reach it through the Vite proxy in dev, which now sets the backend's Host on WebSocket upgrades as it already did for HTTP requests. serve() now takes ServeOptions (UI files, routing setup and a per-run API token) and replaces serve_with_routing_setup(). Nothing checks the token yet. Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- .env.example | 2 +- crates/fleetify-backend/src/access.rs | 326 ++++++++++++++++++ crates/fleetify-backend/src/http.rs | 39 +-- crates/fleetify-backend/src/lib.rs | 65 ++-- .../fleetify-backend/src/routers/browser.rs | 5 +- .../fleetify-backend/src/routers/internal.rs | 22 +- .../src/services/routing/setup.rs | 12 +- .../src/services/telemetry/posthog/mod.rs | 2 +- crates/fleetify-backend/tests/access.rs | 136 ++++++++ crates/fleetify-backend/tests/auth_noauth.rs | 7 +- crates/fleetify-backend/tests/common/mod.rs | 54 +++ .../tests/container_sessions.rs | 7 +- .../tests/fleet_delegate_api.rs | 15 +- crates/fleetify-backend/tests/healthz.rs | 7 +- crates/fleetify-backend/tests/phase4_apis.rs | 6 +- .../tests/serves_real_dist.rs | 13 +- crates/fleetify-backend/tests/sessions_api.rs | 6 +- .../fleetify-backend/tests/spawn_endpoint.rs | 7 +- crates/fleetify-backend/tests/static_dir.rs | 15 +- .../tests/worktree_next_round.rs | 7 +- crates/fleetify-backend/tests/ws_protocol.rs | 6 +- docs/ROUTING.md | 4 +- src-tauri/src/lib.rs | 7 +- src-tauri/src/shell/backend_ready.rs | 4 +- src-tauri/src/shell/routing_setup.rs | 6 +- vite.config.ts | 4 +- 26 files changed, 676 insertions(+), 108 deletions(-) create mode 100644 crates/fleetify-backend/src/access.rs create mode 100644 crates/fleetify-backend/tests/access.rs create mode 100644 crates/fleetify-backend/tests/common/mod.rs diff --git a/.env.example b/.env.example index 26b2738..090787d 100644 --- a/.env.example +++ b/.env.example @@ -2,7 +2,7 @@ # # Only debug builds read `.env` at runtime. In a debug build # (`npm run dev:tauri`), `dotenvy` loads it into the backend's process env -# at the top of `serve_with_routing_setup` so the Rust side picks it up via +# at the top of `serve` so the Rust side picks it up via # `std::env::var`. Release builds never read it: a project's `.env` in the # directory Fleetify is launched from must not configure the app. Existing # shell env wins — set values here are a fallback. diff --git a/crates/fleetify-backend/src/access.rs b/crates/fleetify-backend/src/access.rs new file mode 100644 index 0000000..2a55685 --- /dev/null +++ b/crates/fleetify-backend/src/access.rs @@ -0,0 +1,326 @@ +//! Who the embedded backend answers. +//! +//! The backend listens on `127.0.0.1:` for the app alone: its window, +//! the shell and the agents' helper processes. A request has to be addressed +//! to that host, `127.0.0.1:` or `localhost:`; any other gets a +//! plain-text 403. [`guard`] is the router's outermost layer +//! (`http::app`), so this holds for every path: the API, `/healthz`, the UI +//! files and the 404s. +//! +//! Each run also has an [`ApiToken`]. The shell makes it at startup, passes +//! it to [`crate::serve`] and gives it to the renderer over IPC +//! (`backend_api_token`). + +use std::fmt; +use std::fmt::Write as _; +use std::sync::Arc; + +use axum::extract::{Request, State}; +use axum::http::{header, StatusCode}; +use axum::middleware::Next; +use axum::response::{IntoResponse, Response}; +use rand::RngCore; + +/// The request header that carries the per-run token. +pub const API_TOKEN_HEADER: &str = "x-fleetify-token"; +/// The query parameter that carries it on URLs that can't set a header +/// (WebSocket and EventSource). +pub const API_TOKEN_QUERY: &str = "api_token"; + +/// This run's API token. Its `Debug` never shows the value. +#[derive(Clone)] +pub struct ApiToken(Arc); + +impl ApiToken { + /// 32 random bytes, as 64 lowercase hex characters. + pub fn generate() -> Self { + let mut bytes = [0u8; 32]; + rand::thread_rng().fill_bytes(&mut bytes); + let mut hex = String::with_capacity(64); + for b in bytes { + let _ = write!(hex, "{b:02x}"); + } + Self(Arc::from(hex)) + } + + pub fn as_str(&self) -> &str { + &self.0 + } + + /// Whether `candidate` is this token, compared in constant time. + pub fn matches(&self, candidate: &str) -> bool { + constant_time_eq(self.0.as_bytes(), candidate.as_bytes()) + } +} + +impl fmt::Debug for ApiToken { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ApiToken(..)") + } +} + +/// What [`guard`] checks requests against. +#[derive(Clone)] +pub struct AccessPolicy { + /// The port the backend bound. + pub port: u16, + /// This run's token. + pub token: ApiToken, +} + +/// Whether `host`, a request's `Host` (or its URI authority), is the +/// backend's own address: `127.0.0.1:` or `localhost:`, in any +/// letter case. Another port, no port, another name or no host is refused. +pub fn host_allowed(host: Option<&str>, port: u16) -> bool { + host.is_some_and(|host| { + ["127.0.0.1", "localhost"] + .iter() + .any(|name| host.eq_ignore_ascii_case(&format!("{name}:{port}"))) + }) +} + +/// Constant-time byte-slice equality. Tiny implementation — fine for +/// 32-byte secrets like the loopback token. +pub(crate) fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { + if a.len() != b.len() { + return false; + } + let mut diff: u8 = 0; + for (x, y) in a.iter().zip(b.iter()) { + diff |= x ^ y; + } + diff == 0 +} + +/// The router's outermost layer: a request that isn't addressed to the +/// backend's own host gets a plain-text 403. +pub async fn guard(State(policy): State, req: Request, next: Next) -> Response { + if !host_allowed(request_host(&req), policy.port) { + return refuse("host", &req); + } + next.run(req).await +} + +/// The host a request is addressed to: its `Host` header, or the URI's +/// authority when it has no `Host` header. A request with two `Host` +/// headers has none. +fn request_host(req: &Request) -> Option<&str> { + let mut hosts = req.headers().get_all(header::HOST).iter(); + match (hosts.next(), hosts.next()) { + (Some(host), None) => host.to_str().ok(), + (None, _) => req.uri().authority().map(|authority| authority.as_str()), + (Some(_), Some(_)) => None, + } +} + +/// The 403. The log line has the path without its query string, which can +/// carry a token. +fn refuse(reason: &'static str, req: &Request) -> Response { + tracing::warn!( + target: "fleetify.access", + reason, + method = %req.method(), + path = req.uri().path(), + "request refused" + ); + (StatusCode::FORBIDDEN, "forbidden").into_response() +} + +#[cfg(test)] +mod tests { + use std::sync::Mutex; + + use axum::body::Body; + use axum::http::Request; + use axum::middleware::from_fn_with_state; + use axum::routing::get; + use axum::Router; + use tower::ServiceExt; + + use super::*; + + #[test] + fn the_backends_own_address_is_allowed_in_any_letter_case() { + for host in ["127.0.0.1:8765", "localhost:8765", "LOCALHOST:8765"] { + assert!(host_allowed(Some(host), 8765), "{host} was refused"); + } + } + + #[test] + fn any_other_host_is_refused() { + for host in [ + "127.0.0.1:8766", + "127.0.0.1", + "evil.example:8765", + "127.0.0.1.evil.example:8765", + "[::1]:8765", + ] { + assert!(!host_allowed(Some(host), 8765), "{host} was allowed"); + } + assert!(!host_allowed(None, 8765), "a missing host was allowed"); + } + + // The token assertions never print a token: a failure message says what + // is wrong, not the value. + + #[test] + fn a_generated_token_is_64_lowercase_hex_characters_and_new_each_time() { + let token = ApiToken::generate(); + assert_eq!(token.as_str().len(), 64); + assert!( + token + .as_str() + .chars() + .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c)), + "the token is not lowercase hex" + ); + assert!( + token.as_str() != ApiToken::generate().as_str(), + "two generated tokens are equal" + ); + } + + #[test] + fn a_token_matches_only_itself() { + let token = ApiToken::generate(); + assert!(token.matches(token.as_str()), "the token itself"); + assert!(!token.matches(""), "the empty string"); + assert!( + !token.matches(&token.as_str()[..63]), + "a 63-character prefix" + ); + assert!( + !token.matches(ApiToken::generate().as_str()), + "another token" + ); + } + + #[test] + fn debug_never_shows_the_token() { + let token = ApiToken::generate(); + let shown = format!("{token:?}"); + assert!(!shown.contains(token.as_str()), "Debug shows the token"); + assert!(shown == "ApiToken(..)", "Debug isn't ApiToken(..)"); + } + + #[test] + fn constant_time_eq_handles_length_mismatch_and_match() { + assert!(constant_time_eq(b"abc", b"abc")); + assert!(!constant_time_eq(b"abc", b"abd")); + assert!(!constant_time_eq(b"abc", b"abcd")); + assert!(constant_time_eq(b"", b"")); + } + + /// One route behind the guard, for a backend bound to port 8765. + async fn through_guard(req: Request) -> (StatusCode, String) { + let policy = AccessPolicy { + port: 8765, + token: ApiToken::generate(), + }; + let app = Router::new() + .route("/api/x", get(|| async { "ok" }).post(|| async { "ok" })) + .layer(from_fn_with_state(policy, guard)); + let resp = app.oneshot(req).await.unwrap(); + let status = resp.status(); + let body = axum::body::to_bytes(resp.into_body(), usize::MAX) + .await + .unwrap(); + (status, String::from_utf8_lossy(&body).into_owned()) + } + + fn request(uri: &str, hosts: &[&str]) -> Request { + let mut req = Request::builder().uri(uri); + for host in hosts { + req = req.header("host", *host); + } + req.body(Body::empty()).unwrap() + } + + #[tokio::test] + async fn the_guard_checks_the_host_header_or_else_the_uri_authority() { + let ok = (StatusCode::OK, "ok".to_string()); + let forbidden = (StatusCode::FORBIDDEN, "forbidden".to_string()); + + assert_eq!( + through_guard(request("/api/x", &["127.0.0.1:8765"])).await, + ok + ); + assert_eq!( + through_guard(request("/api/x", &["evil.example:8765"])).await, + forbidden + ); + // No Host header: the URI's authority is checked instead. + assert_eq!( + through_guard(request("http://localhost:8765/api/x", &[])).await, + ok + ); + assert_eq!( + through_guard(request("http://evil.example:8765/api/x", &[])).await, + forbidden + ); + assert_eq!(through_guard(request("/api/x", &[])).await, forbidden); + // Two Host headers count as none. + assert_eq!( + through_guard(request("/api/x", &["127.0.0.1:8765", "evil.example:8765"])).await, + forbidden + ); + } + + #[tokio::test] + async fn a_refusal_is_logged_with_its_path_and_never_its_query() { + let logs = LogCapture::start(); + let req = Request::builder() + .method("POST") + .uri("/api/x?api_token=query-SECRET") + .header("host", "evil.example:8765") + .body(Body::empty()) + .unwrap(); + let (status, _) = through_guard(req).await; + let text = logs.text(); + + assert_eq!(status, StatusCode::FORBIDDEN); + assert!(text.contains("WARN fleetify.access:"), "{text}"); + assert!(text.contains(r#"reason="host""#), "{text}"); + assert!(text.contains("method=POST"), "{text}"); + assert!(text.contains(r#"path="/api/x""#), "{text}"); + assert!(!text.contains("SECRET"), "the query string was logged"); + } + + /// Everything logged on this thread while it lives, as plain text. + struct LogCapture { + lines: Arc>>, + _guard: tracing::subscriber::DefaultGuard, + } + + impl LogCapture { + fn start() -> Self { + let lines = Arc::new(Mutex::new(Vec::new())); + let sink = Arc::clone(&lines); + let subscriber = tracing_subscriber::fmt() + .with_max_level(tracing::Level::TRACE) + .with_ansi(false) + .with_writer(move || CaptureWriter(Arc::clone(&sink))) + .finish(); + Self { + lines, + _guard: tracing::subscriber::set_default(subscriber), + } + } + + fn text(&self) -> String { + String::from_utf8_lossy(&self.lines.lock().unwrap()).into_owned() + } + } + + struct CaptureWriter(Arc>>); + + impl std::io::Write for CaptureWriter { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } +} diff --git a/crates/fleetify-backend/src/http.rs b/crates/fleetify-backend/src/http.rs index 7eef813..b8e248e 100644 --- a/crates/fleetify-backend/src/http.rs +++ b/crates/fleetify-backend/src/http.rs @@ -1,11 +1,11 @@ use std::path::PathBuf; -use axum::http::{HeaderValue, Method}; +use axum::middleware::from_fn_with_state; use axum::{routing::get, Json, Router}; use serde_json::{json, Value}; -use tower_http::cors::CorsLayer; use tower_http::services::ServeDir; +use crate::access::{self, AccessPolicy}; use crate::routers::{ accounts, auth as auth_router, browser, chat, docker, events, fleet, fs, groups, internal, library, marketplace, mcp, messages, plugins, prompt, prompts, providers, routing, runtime, @@ -18,27 +18,10 @@ pub const HEALTH_PATH: &str = "/healthz"; /// Build the axum app. Single origin: `/healthz`, `/api/*` (auth'd), /// `/events/status` SSE, and the built React assets (when `static_dir`). -/// CORS mirrors the Python: localhost:3000 / 127.0.0.1:3000, creds, *. -pub fn app(state: AppState, static_dir: Option) -> Router { - let cors = CorsLayer::new() - .allow_origin([ - "http://localhost:3000".parse::().unwrap(), - "http://127.0.0.1:3000".parse::().unwrap(), - ]) - .allow_credentials(true) - .allow_methods([ - Method::GET, - Method::POST, - Method::PATCH, - Method::DELETE, - Method::OPTIONS, - Method::PUT, - ]) - // Starlette's `allow_headers=["*"]` + credentials maps to - // mirroring the requested headers in tower-http (Any + credentials - // is rejected at construction). - .allow_headers(tower_http::cors::AllowHeaders::mirror_request()); - +/// No CORS: the app's pages come from this origin (or, in dev, through the +/// Vite proxy). [`access::guard`] wraps all of it, the static files and the +/// 404s included. +pub fn app(state: AppState, static_dir: Option, policy: AccessPolicy) -> Router { let api = sessions::router() .merge(messages::router()) .merge(groups::router()) @@ -75,13 +58,15 @@ pub fn app(state: AppState, static_dir: Option) -> Router { .merge(events::router()) .merge(chat::router()) .merge(browser::ws_router()) - .with_state(state) - .layer(cors); + .with_state(state); - match static_dir { + let routed = match static_dir { Some(dir) => routed.fallback_service(ServeDir::new(dir)), None => routed, - } + }; + // Last, so it is the outermost layer: axum applies a layer only to the + // routes and fallback added before it. + routed.layer(from_fn_with_state(policy, access::guard)) } async fn healthz() -> Json { diff --git a/crates/fleetify-backend/src/lib.rs b/crates/fleetify-backend/src/lib.rs index 82d4245..89f74fc 100644 --- a/crates/fleetify-backend/src/lib.rs +++ b/crates/fleetify-backend/src/lib.rs @@ -5,6 +5,7 @@ mod http; +pub mod access; pub mod agentic; pub mod auth; pub mod bridges; @@ -103,20 +104,31 @@ async fn normalize_legacy_verbatim_project_paths(pool: &sqlx::SqlitePool) { } } -/// Bind `addr` and start serving on a background task. `static_dir` is the -/// built React asset directory for single-origin serving (`None` = API only). -/// -/// Convenience wrapper around `serve_with_routing_setup` for callers that -/// don't have hydrated router credentials (tests, headless dev runs). -/// External routers stay un-registered — only builtin + DirectGateway are -/// available, and the master toggle defaults to OFF. -pub async fn serve(addr: SocketAddr, static_dir: Option) -> anyhow::Result { - serve_with_routing_setup( - addr, - static_dir, - services::routing::setup::RoutingSetup::default(), - ) - .await +/// What [`serve`] starts with. +pub struct ServeOptions { + /// The built React asset directory for single-origin serving (`None` = + /// API only). + pub static_dir: Option, + /// The external routers to hydrate the routing orchestrator with. The + /// Tauri shell composes it from `fleet.config.json` + the per-user + /// keychain, so the backend stays Tauri-agnostic. + pub routing_setup: services::routing::setup::RoutingSetup, + /// This run's API token. The shell gives the same token to the renderer. + pub api_token: access::ApiToken, +} + +impl ServeOptions { + /// For callers that don't have hydrated router credentials (tests, + /// headless dev runs): no UI files, and external routers stay + /// un-registered — only builtin + DirectGateway are available, and the + /// master toggle defaults to OFF. + pub fn api_only(api_token: access::ApiToken) -> Self { + Self { + static_dir: None, + routing_setup: services::routing::setup::RoutingSetup::default(), + api_token, + } + } } /// Whether this instance should isolate its sessions DB under FLEETIFY_HOME: @@ -163,15 +175,16 @@ pub(crate) fn should_load_dotenv(release_build: bool) -> bool { !release_build } -/// Bind `addr` and start serving, hydrating the routing orchestrator with -/// the supplied `routing_setup`. The Tauri shell composes the setup from -/// `fleet.config.json` + the per-user keychain before invoking this so -/// the backend stays Tauri-agnostic. -pub async fn serve_with_routing_setup( - addr: SocketAddr, - static_dir: Option, - routing_setup: services::routing::setup::RoutingSetup, -) -> anyhow::Result { +/// Bind `addr` and start serving on a background task, with the UI files, +/// external routers and API token in `opts`. The access guard +/// ([`access::guard`]) answers only requests addressed to the port actually +/// bound. +pub async fn serve(addr: SocketAddr, opts: ServeOptions) -> anyhow::Result { + let ServeOptions { + static_dir, + routing_setup, + api_token, + } = opts; // Debug builds load the first `.env` found walking up from the working // directory (the workspace root's under `npm run dev:tauri`) into the // process environment. Existing env vars are NOT overridden — a real @@ -393,7 +406,11 @@ pub async fn serve_with_routing_setup( let bg_pool = state.auth.pool.clone(); let bg_sm = state.sm; let bg_cfg = state.app_cfg.clone(); - let router = app(state, static_dir); + let policy = access::AccessPolicy { + port: local_addr.port(), + token: api_token, + }; + let router = app(state, static_dir, policy); tokio::spawn(async move { let server = axum::serve(listener, router).with_graceful_shutdown(async { let _ = shutdown_rx.await; diff --git a/crates/fleetify-backend/src/routers/browser.rs b/crates/fleetify-backend/src/routers/browser.rs index f6473b8..5b53b14 100644 --- a/crates/fleetify-backend/src/routers/browser.rs +++ b/crates/fleetify-backend/src/routers/browser.rs @@ -210,10 +210,7 @@ async fn action( .get("x-fleet-internal") .and_then(|v| v.to_str().ok()) .unwrap_or(""); - if !crate::routers::internal::constant_time_eq( - presented.as_bytes(), - st.internal_secret.as_bytes(), - ) { + if !crate::access::constant_time_eq(presented.as_bytes(), st.internal_secret.as_bytes()) { return Err(StatusCode::FORBIDDEN); } Ok(Json(match browser::action(&b.name, &b.args).await { diff --git a/crates/fleetify-backend/src/routers/internal.rs b/crates/fleetify-backend/src/routers/internal.rs index 998c898..73f6a06 100644 --- a/crates/fleetify-backend/src/routers/internal.rs +++ b/crates/fleetify-backend/src/routers/internal.rs @@ -28,6 +28,7 @@ use axum::{Json, Router}; use serde::Deserialize; use serde_json::{json, Value}; +use crate::access::constant_time_eq; use crate::models::session::Session; use crate::routers::{ApiError, AppState}; @@ -745,19 +746,6 @@ async fn providers_warm_health( Ok(Json(json!({ "ok": true, "warmed": cached.len() }))) } -/// Constant-time byte-slice equality. Tiny implementation — fine for -/// 32-byte secrets like the loopback token. -pub(crate) fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { - if a.len() != b.len() { - return false; - } - let mut diff: u8 = 0; - for (x, y) in a.iter().zip(b.iter()) { - diff |= x ^ y; - } - diff == 0 -} - #[allow(dead_code)] fn _silence_unused_status_code(_: StatusCode) {} @@ -1124,14 +1112,6 @@ mod tests { assert_eq!(resp.status(), 400); } - #[test] - fn constant_time_eq_handles_length_mismatch_and_match() { - assert!(constant_time_eq(b"abc", b"abc")); - assert!(!constant_time_eq(b"abc", b"abd")); - assert!(!constant_time_eq(b"abc", b"abcd")); - assert!(constant_time_eq(b"", b"")); - } - #[tokio::test] async fn warm_health_writes_cache_for_every_keyed_provider() { use crate::routers::providers::{HealthSnapshot, HttpHealthCache}; diff --git a/crates/fleetify-backend/src/services/routing/setup.rs b/crates/fleetify-backend/src/services/routing/setup.rs index 4526eb8..0d37b24 100644 --- a/crates/fleetify-backend/src/services/routing/setup.rs +++ b/crates/fleetify-backend/src/services/routing/setup.rs @@ -1,7 +1,7 @@ //! Resolved router credentials passed from the Tauri shell into the //! embedded backend at startup. The shell reads `fleet.config.json` //! plus the per-user keychain, composes a `RoutingSetup`, and hands -//! it to `serve_with_routing_setup()` — keeping the backend Tauri- +//! it to `serve()` (in its `ServeOptions`) — keeping the backend Tauri- //! agnostic while still allowing it to register external routers //! (Not Diamond, Weave, LiteLLM) without round-tripping IPC at boot. @@ -21,11 +21,11 @@ pub struct ResolvedRouterCredential { /// live IPC-triggered reload. /// /// Composed on the Tauri side from `fleet.config.json` + the user's -/// keychain entries, then either passed into `serve_with_routing_setup()` -/// at boot or POSTed to `/api/internal/routing/reload` while the backend -/// is already running. `enabled` is the master "intelligent routing" -/// toggle; the two `active_*` ids are the saved user selections (default -/// builtin / none-proxy when unset). +/// keychain entries, then either passed into `serve()` (in its +/// `ServeOptions`) at boot or POSTed to `/api/internal/routing/reload` +/// while the backend is already running. `enabled` is the master +/// "intelligent routing" toggle; the two `active_*` ids are the saved user +/// selections (default builtin / none-proxy when unset). #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct RoutingSetup { pub enabled: bool, diff --git a/crates/fleetify-backend/src/services/telemetry/posthog/mod.rs b/crates/fleetify-backend/src/services/telemetry/posthog/mod.rs index f25118b..04aa6f6 100644 --- a/crates/fleetify-backend/src/services/telemetry/posthog/mod.rs +++ b/crates/fleetify-backend/src/services/telemetry/posthog/mod.rs @@ -9,7 +9,7 @@ //! Three-tier gating, fail-closed: //! 1. Environment: `POSTHOG_API_KEY` present in the process env when //! `init()` runs (loaded from `.env` by `dotenvy` at the top of -//! `serve_with_routing_setup`, or set in the shell). Unset → +//! `serve`, or set in the shell). Unset → //! `init` is a no-op, `enqueue_if_enabled` short-circuits. //! 2. Runtime: `ENABLED` AtomicBool. Tauri shell flips it via the //! `telemetry_set_posthog_enabled` command after user consent. diff --git a/crates/fleetify-backend/tests/access.rs b/crates/fleetify-backend/tests/access.rs new file mode 100644 index 0000000..fd7d18f --- /dev/null +++ b/crates/fleetify-backend/tests/access.rs @@ -0,0 +1,136 @@ +//! The access guard over the real `serve()` stack: the backend answers only +//! requests addressed to its own host (`127.0.0.1:` or +//! `localhost:`), on every path, and sends no CORS headers. + +mod common; + +use std::net::SocketAddr; +use std::time::Duration; + +use common::TestServer; +use fleetify_backend::access::ApiToken; +use fleetify_backend::ServeOptions; + +fn in_memory_db() { + std::env::set_var("FLEET_DB_URL", "sqlite::memory:"); +} + +async fn start() -> TestServer { + in_memory_db(); + TestServer::start().await +} + +/// `GET path` with `host` as the Host header. +async fn get_with_host(server: &TestServer, path: &str, host: &str) -> reqwest::Response { + reqwest::Client::new() + .get(server.url(path)) + .header(reqwest::header::HOST, host) + .send() + .await + .unwrap() +} + +/// Send `request` over a plain TCP connection and return the raw response. +async fn raw_exchange(addr: SocketAddr, request: &str) -> String { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let exchange = async { + let mut stream = tokio::net::TcpStream::connect(addr).await.unwrap(); + stream.write_all(request.as_bytes()).await.unwrap(); + let mut response = Vec::new(); + stream.read_to_end(&mut response).await.unwrap(); + response + }; + let response = tokio::time::timeout(Duration::from_secs(10), exchange) + .await + .expect("the server closes an HTTP/1.0 connection after its response"); + String::from_utf8_lossy(&response).into_owned() +} + +#[tokio::test] +async fn healthz_answers_on_its_own_address() { + let server = start().await; + let resp = reqwest::get(server.url("/healthz")).await.unwrap(); + assert_eq!(resp.status(), 200); +} + +#[tokio::test] +async fn another_host_gets_a_plain_text_403_on_every_path() { + let server = start().await; + let evil = format!("evil.example:{}", server.port()); + + let resp = get_with_host(&server, "/healthz", &evil).await; + assert_eq!(resp.status(), 403); + assert_eq!(resp.text().await.unwrap(), "forbidden"); + + // A path no route matches: the 404 is behind the check too. + let own = format!("127.0.0.1:{}", server.port()); + let resp = get_with_host(&server, "/no-such-path", &own).await; + assert_eq!(resp.status(), 404); + let resp = get_with_host(&server, "/no-such-path", &evil).await; + assert_eq!(resp.status(), 403); +} + +#[tokio::test] +async fn localhost_on_the_bound_port_is_allowed() { + let server = start().await; + let host = format!("localhost:{}", server.port()); + let resp = get_with_host(&server, "/healthz", &host).await; + assert_eq!(resp.status(), 200); +} + +/// hyper accepts an HTTP/1.0 request without a Host header; the guard is +/// what refuses it (its plain-text body says so). +#[tokio::test] +async fn a_request_without_a_host_is_refused() { + let server = start().await; + let response = raw_exchange(server.addr(), "GET /healthz HTTP/1.0\r\n\r\n").await; + let status_line = response.lines().next().unwrap_or_default(); + assert!( + status_line.starts_with("HTTP/1.") && status_line.contains(" 403 "), + "status line: {status_line}" + ); + assert!(response.ends_with("\r\n\r\nforbidden"), "{response}"); +} + +#[tokio::test] +async fn a_cross_origin_preflight_gets_no_cors_headers() { + let server = start().await; + let resp = reqwest::Client::new() + .request(reqwest::Method::OPTIONS, server.url("/api/groups")) + .header("Origin", "http://localhost:3000") + .header("Access-Control-Request-Method", "POST") + .send() + .await + .unwrap(); + assert!( + resp.headers().get("access-control-allow-origin").is_none(), + "CORS headers sent: {:?}", + resp.headers() + ); +} + +/// The guard is the outermost layer, so the static-file fallback is behind +/// it too: the UI is served to its own address and refused to any other. +#[tokio::test] +async fn the_ui_files_are_behind_the_host_check() { + in_memory_db(); + let ui = tempfile::tempdir().unwrap(); + std::fs::write(ui.path().join("index.html"), "FLEET-UI").unwrap(); + let server = TestServer::start_with(ServeOptions { + static_dir: Some(ui.path().to_path_buf()), + ..ServeOptions::api_only(ApiToken::generate()) + }) + .await; + + let served = reqwest::get(server.url("/")).await.unwrap(); + assert_eq!(served.status(), 200); + assert!(served.text().await.unwrap().contains("FLEET-UI")); + + let evil = format!("evil.example:{}", server.port()); + let refused = get_with_host(&server, "/", &evil).await; + assert_eq!(refused.status(), 403); + assert_eq!(refused.text().await.unwrap(), "forbidden"); + let refused = get_with_host(&server, "/index.html", &evil).await; + assert_eq!(refused.status(), 403); +} diff --git a/crates/fleetify-backend/tests/auth_noauth.rs b/crates/fleetify-backend/tests/auth_noauth.rs index 87edd0d..8993801 100644 --- a/crates/fleetify-backend/tests/auth_noauth.rs +++ b/crates/fleetify-backend/tests/auth_noauth.rs @@ -8,6 +8,9 @@ use std::net::SocketAddr; +use fleetify_backend::access::ApiToken; +use fleetify_backend::ServeOptions; + fn enable_noauth() { std::env::set_var("FLEETIFY_NOAUTH", "1"); // Point JWKS at a dead address — the bypass must NOT touch it. If the @@ -26,7 +29,9 @@ async fn protected_route_skips_bearer_when_noauth_enabled() { ); let addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); - let handle = fleetify_backend::serve(addr, None).await.expect("serve"); + let handle = fleetify_backend::serve(addr, ServeOptions::api_only(ApiToken::generate())) + .await + .expect("serve"); let base = format!("http://{}", handle.local_addr()); // No Authorization header — would normally 401 NotAuthenticated. diff --git a/crates/fleetify-backend/tests/common/mod.rs b/crates/fleetify-backend/tests/common/mod.rs new file mode 100644 index 0000000..b28c8b0 --- /dev/null +++ b/crates/fleetify-backend/tests/common/mod.rs @@ -0,0 +1,54 @@ +//! Shared by the integration tests: the real backend, started with +//! `serve()` on an ephemeral loopback port. A test file pulls it in with +//! `mod common;`. +//! +//! It sets no environment variables: each test still sets the ones it needs +//! (`FLEET_DB_URL`, `FLEETIFY_NOAUTH`, …) before it starts a server, and the +//! ones `serve()` sets (`FLEETIFY_BACKEND_URL`, `FLEETIFY_INTERNAL_SECRET`) +//! are there once a start returns. + +// Each test binary compiles its own copy and uses only some of it. +#![allow(dead_code)] + +use std::net::SocketAddr; + +use fleetify_backend::access::ApiToken; +use fleetify_backend::{ServeOptions, ServerHandle}; + +/// A running backend. Dropping it shuts the server down, so keep it alive +/// while the test sends requests. +pub struct TestServer { + pub handle: ServerHandle, + /// The token the server was started with. + pub token: ApiToken, +} + +impl TestServer { + /// API only (no UI files, no external routers), with a new token. + pub async fn start() -> Self { + Self::start_with(ServeOptions::api_only(ApiToken::generate())).await + } + + /// Started with `opts`, on `127.0.0.1:0`. + pub async fn start_with(opts: ServeOptions) -> Self { + let token = opts.api_token.clone(); + let addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); + let handle = fleetify_backend::serve(addr, opts).await.expect("serve"); + Self { handle, token } + } + + /// The address it bound. + pub fn addr(&self) -> SocketAddr { + self.handle.local_addr() + } + + /// The port it bound. + pub fn port(&self) -> u16 { + self.addr().port() + } + + /// `http://127.0.0.1:`. + pub fn url(&self, path: &str) -> String { + format!("http://{}{path}", self.addr()) + } +} diff --git a/crates/fleetify-backend/tests/container_sessions.rs b/crates/fleetify-backend/tests/container_sessions.rs index 52190d7..24c8571 100644 --- a/crates/fleetify-backend/tests/container_sessions.rs +++ b/crates/fleetify-backend/tests/container_sessions.rs @@ -12,6 +12,9 @@ use std::net::SocketAddr; +use fleetify_backend::access::ApiToken; +use fleetify_backend::ServeOptions; + fn enable_noauth() { std::env::set_var("FLEETIFY_NOAUTH", "1"); // Dead JWKS address: the bypass must never reach out. If it ever does, @@ -28,7 +31,9 @@ fn enable_noauth() { async fn boot() -> (String, fleetify_backend::ServerHandle) { enable_noauth(); let addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); - let handle = fleetify_backend::serve(addr, None).await.expect("serve"); + let handle = fleetify_backend::serve(addr, ServeOptions::api_only(ApiToken::generate())) + .await + .expect("serve"); (format!("http://{}", handle.local_addr()), handle) } diff --git a/crates/fleetify-backend/tests/fleet_delegate_api.rs b/crates/fleetify-backend/tests/fleet_delegate_api.rs index 64ee0a9..2a856b9 100644 --- a/crates/fleetify-backend/tests/fleet_delegate_api.rs +++ b/crates/fleetify-backend/tests/fleet_delegate_api.rs @@ -11,6 +11,9 @@ use std::net::SocketAddr; +use fleetify_backend::access::ApiToken; +use fleetify_backend::ServeOptions; + fn enable_noauth() { std::env::set_var("FLEETIFY_NOAUTH", "1"); std::env::set_var("FLEETIFY_ISSUER", "http://127.0.0.1:1"); @@ -22,7 +25,9 @@ fn enable_noauth() { async fn delegate_without_staff_session_is_400() { enable_noauth(); let addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); - let handle = fleetify_backend::serve(addr, None).await.expect("serve"); + let handle = fleetify_backend::serve(addr, ServeOptions::api_only(ApiToken::generate())) + .await + .expect("serve"); let base = format!("http://{}", handle.local_addr()); let resp = reqwest::Client::new() @@ -43,7 +48,9 @@ async fn delegate_without_staff_session_is_400() { async fn delegate_empty_dispatches_is_400() { enable_noauth(); let addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); - let handle = fleetify_backend::serve(addr, None).await.expect("serve"); + let handle = fleetify_backend::serve(addr, ServeOptions::api_only(ApiToken::generate())) + .await + .expect("serve"); let base = format!("http://{}", handle.local_addr()); let resp = reqwest::Client::new() @@ -59,7 +66,9 @@ async fn delegate_empty_dispatches_is_400() { async fn delegate_status_unknown_batch_is_404() { enable_noauth(); let addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); - let handle = fleetify_backend::serve(addr, None).await.expect("serve"); + let handle = fleetify_backend::serve(addr, ServeOptions::api_only(ApiToken::generate())) + .await + .expect("serve"); let base = format!("http://{}", handle.local_addr()); let resp = reqwest::Client::new() diff --git a/crates/fleetify-backend/tests/healthz.rs b/crates/fleetify-backend/tests/healthz.rs index cfb1cc8..76e687f 100644 --- a/crates/fleetify-backend/tests/healthz.rs +++ b/crates/fleetify-backend/tests/healthz.rs @@ -1,10 +1,15 @@ use std::net::SocketAddr; +use fleetify_backend::access::ApiToken; +use fleetify_backend::ServeOptions; + #[tokio::test] async fn healthz_returns_ok_json() { std::env::set_var("FLEET_DB_URL", "sqlite::memory:"); let addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); - let handle = fleetify_backend::serve(addr, None).await.expect("serve"); + let handle = fleetify_backend::serve(addr, ServeOptions::api_only(ApiToken::generate())) + .await + .expect("serve"); let bound = handle.local_addr(); let body = reqwest::get(format!("http://{bound}/healthz")) diff --git a/crates/fleetify-backend/tests/phase4_apis.rs b/crates/fleetify-backend/tests/phase4_apis.rs index e50d27a..fc65962 100644 --- a/crates/fleetify-backend/tests/phase4_apis.rs +++ b/crates/fleetify-backend/tests/phase4_apis.rs @@ -9,6 +9,8 @@ use std::net::SocketAddr; use std::time::{SystemTime, UNIX_EPOCH}; use base64::Engine; +use fleetify_backend::access::ApiToken; +use fleetify_backend::ServeOptions; use jsonwebtoken::{encode, EncodingKey, Header}; use rsa::pkcs8::EncodePrivateKey; use rsa::traits::PublicKeyParts; @@ -72,7 +74,9 @@ async fn phase4_apis_smoke() { // 4. Start backend on an ephemeral port. let addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); - let handle = fleetify_backend::serve(addr, None).await.unwrap(); + let handle = fleetify_backend::serve(addr, ServeOptions::api_only(ApiToken::generate())) + .await + .unwrap(); let base = format!("http://{}", handle.local_addr()); let client = reqwest::Client::new(); diff --git a/crates/fleetify-backend/tests/serves_real_dist.rs b/crates/fleetify-backend/tests/serves_real_dist.rs index 7f28273..27cc7d5 100644 --- a/crates/fleetify-backend/tests/serves_real_dist.rs +++ b/crates/fleetify-backend/tests/serves_real_dist.rs @@ -6,6 +6,9 @@ use std::net::SocketAddr; use std::path::PathBuf; +use fleetify_backend::access::ApiToken; +use fleetify_backend::ServeOptions; + #[tokio::test] #[ignore = "requires dist/ from `npm run build`; run with --ignored"] async fn serves_real_react_bundle_and_healthz_same_origin() { @@ -17,7 +20,15 @@ async fn serves_real_react_bundle_and_healthz_same_origin() { ); let addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); - let h = fleetify_backend::serve(addr, Some(dist)).await.unwrap(); + let h = fleetify_backend::serve( + addr, + ServeOptions { + static_dir: Some(dist), + ..ServeOptions::api_only(ApiToken::generate()) + }, + ) + .await + .unwrap(); let base = format!("http://{}", h.local_addr()); // /healthz coexists with static serving. diff --git a/crates/fleetify-backend/tests/sessions_api.rs b/crates/fleetify-backend/tests/sessions_api.rs index 9b88f57..17b6b33 100644 --- a/crates/fleetify-backend/tests/sessions_api.rs +++ b/crates/fleetify-backend/tests/sessions_api.rs @@ -6,6 +6,8 @@ use std::net::SocketAddr; use std::time::{SystemTime, UNIX_EPOCH}; use base64::Engine; +use fleetify_backend::access::ApiToken; +use fleetify_backend::ServeOptions; use jsonwebtoken::{encode, EncodingKey, Header}; use rsa::pkcs8::EncodePrivateKey; use rsa::traits::PublicKeyParts; @@ -54,7 +56,9 @@ async fn sessions_api_round_trip_with_auth() { // 4. Boot the real backend. let addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); - let handle = fleetify_backend::serve(addr, None).await.expect("serve"); + let handle = fleetify_backend::serve(addr, ServeOptions::api_only(ApiToken::generate())) + .await + .expect("serve"); let base = format!("http://{}", handle.local_addr()); // 5. Mint a valid JWT (iss = auth_base, aud = expected). diff --git a/crates/fleetify-backend/tests/spawn_endpoint.rs b/crates/fleetify-backend/tests/spawn_endpoint.rs index 1ffa094..f1280bf 100644 --- a/crates/fleetify-backend/tests/spawn_endpoint.rs +++ b/crates/fleetify-backend/tests/spawn_endpoint.rs @@ -6,6 +6,9 @@ use std::net::SocketAddr; +use fleetify_backend::access::ApiToken; +use fleetify_backend::ServeOptions; + fn enable_noauth() { std::env::set_var("FLEETIFY_NOAUTH", "1"); std::env::set_var("FLEETIFY_ISSUER", "http://127.0.0.1:1"); @@ -21,7 +24,9 @@ fn enable_noauth() { async fn spawn_endpoints() { enable_noauth(); let addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); - let handle = fleetify_backend::serve(addr, None).await.expect("serve"); + let handle = fleetify_backend::serve(addr, ServeOptions::api_only(ApiToken::generate())) + .await + .expect("serve"); let base = format!("http://{}", handle.local_addr()); let client = reqwest::Client::new(); let tmp = std::env::temp_dir().to_string_lossy().to_string(); diff --git a/crates/fleetify-backend/tests/static_dir.rs b/crates/fleetify-backend/tests/static_dir.rs index 41bfa8a..5327d02 100644 --- a/crates/fleetify-backend/tests/static_dir.rs +++ b/crates/fleetify-backend/tests/static_dir.rs @@ -1,5 +1,8 @@ use std::net::SocketAddr; +use fleetify_backend::access::ApiToken; +use fleetify_backend::ServeOptions; + #[tokio::test] async fn serves_index_from_static_dir() { std::env::set_var("FLEET_DB_URL", "sqlite::memory:"); @@ -7,9 +10,15 @@ async fn serves_index_from_static_dir() { std::fs::write(dir.path().join("index.html"), "FLEET").unwrap(); let addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); - let h = fleetify_backend::serve(addr, Some(dir.path().to_path_buf())) - .await - .unwrap(); + let h = fleetify_backend::serve( + addr, + ServeOptions { + static_dir: Some(dir.path().to_path_buf()), + ..ServeOptions::api_only(ApiToken::generate()) + }, + ) + .await + .unwrap(); let body = reqwest::get(format!("http://{}/", h.local_addr())) .await diff --git a/crates/fleetify-backend/tests/worktree_next_round.rs b/crates/fleetify-backend/tests/worktree_next_round.rs index 17b568e..2ce3eb1 100644 --- a/crates/fleetify-backend/tests/worktree_next_round.rs +++ b/crates/fleetify-backend/tests/worktree_next_round.rs @@ -9,6 +9,9 @@ use std::net::SocketAddr; use std::process::Command; +use fleetify_backend::access::ApiToken; +use fleetify_backend::ServeOptions; + fn enable_noauth() { std::env::set_var("FLEETIFY_NOAUTH", "1"); std::env::set_var("FLEETIFY_ISSUER", "http://127.0.0.1:1"); @@ -50,7 +53,9 @@ async fn next_round_advances_worktree_and_branch() { clean_repo(&project); let addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); - let handle = fleetify_backend::serve(addr, None).await.expect("serve"); + let handle = fleetify_backend::serve(addr, ServeOptions::api_only(ApiToken::generate())) + .await + .expect("serve"); let base = format!("http://{}", handle.local_addr()); let client = reqwest::Client::new(); diff --git a/crates/fleetify-backend/tests/ws_protocol.rs b/crates/fleetify-backend/tests/ws_protocol.rs index ffc3d0b..6a75e1c 100644 --- a/crates/fleetify-backend/tests/ws_protocol.rs +++ b/crates/fleetify-backend/tests/ws_protocol.rs @@ -11,6 +11,8 @@ use std::net::SocketAddr; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use base64::Engine; +use fleetify_backend::access::ApiToken; +use fleetify_backend::ServeOptions; use futures_util::{SinkExt, StreamExt}; use jsonwebtoken::{encode, EncodingKey, Header}; use rsa::pkcs8::EncodePrivateKey; @@ -54,7 +56,9 @@ async fn ws_sessions_subscribe_and_ping() { std::env::set_var("FLEETIFY_AUDIENCE", "http://127.0.0.1:8765"); let addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); - let h = fleetify_backend::serve(addr, None).await.expect("serve"); + let h = fleetify_backend::serve(addr, ServeOptions::api_only(ApiToken::generate())) + .await + .expect("serve"); let base = format!("http://{}", h.local_addr()); let ws_base = format!("ws://{}", h.local_addr()); diff --git a/docs/ROUTING.md b/docs/ROUTING.md index 15927ab..34be3aa 100644 --- a/docs/ROUTING.md +++ b/docs/ROUTING.md @@ -119,8 +119,8 @@ provider. The Tauri shell composes a `RoutingSetup { enabled, active_decision_router, active_proxy_gateway, resolved: {id → {api_key, base_url}} }` from `fleet.config.json` + the OS keychain and hands it to the backend at boot -(`serve_with_routing_setup`) or POSTs it to `/api/internal/routing/reload` while -running. `RoutingOrchestrator::reload_from_setup` wipes external registry +(`serve`, in its `ServeOptions`) or POSTs it to `/api/internal/routing/reload` +while running. `RoutingOrchestrator::reload_from_setup` wipes external registry entries and re-hydrates Not Diamond / Weave / LiteLLM **without an app restart**, so connect/disconnect/activate from Settings → Routers takes effect live. diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index afea434..38836e0 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -496,7 +496,12 @@ pub fn run() { fleetify_backend::services::routing::setup::RoutingSetup::default() } }; - match fleetify_backend::serve_with_routing_setup(addr, sd, routing_setup).await { + let opts = fleetify_backend::ServeOptions { + static_dir: sd, + routing_setup, + api_token: fleetify_backend::access::ApiToken::generate(), + }; + match fleetify_backend::serve(addr, opts).await { Ok(handle) => { std::mem::forget(handle); // backend_bind_ms splits the boot path: this is the diff --git a/src-tauri/src/shell/backend_ready.rs b/src-tauri/src/shell/backend_ready.rs index 504d2bb..014bb3f 100644 --- a/src-tauri/src/shell/backend_ready.rs +++ b/src-tauri/src/shell/backend_ready.rs @@ -31,7 +31,7 @@ const POLL_TIMEOUT: Duration = Duration::from_millis(500); /// What the embedded backend's task has reported about its start. #[derive(Debug, Clone, PartialEq, Eq)] pub enum BackendStart { - /// No report yet: `serve_with_routing_setup` is still running. + /// No report yet: `serve` is still running. Pending, /// It returned `Ok`: the backend listens on its port. Bound, @@ -42,7 +42,7 @@ pub enum BackendStart { /// Why the embedded backend didn't start. #[derive(Debug, Clone, PartialEq, Eq)] pub enum StartFailure { - /// `serve_with_routing_setup` returned `Err` (the error and its causes), + /// `serve` returned `Err` (the error and its causes), /// or its task ended without a report. Backend(String), /// A release build found no UI files to serve, so the backend was never diff --git a/src-tauri/src/shell/routing_setup.rs b/src-tauri/src/shell/routing_setup.rs index cd2d525..406633e 100644 --- a/src-tauri/src/shell/routing_setup.rs +++ b/src-tauri/src/shell/routing_setup.rs @@ -1,8 +1,8 @@ //! Compose the embedded backend's `RoutingSetup` from on-disk config //! (`fleet.config.json`) and the per-user keychain. Called once from the -//! Tauri setup hook before `fleetify_backend::serve_with_routing_setup` -//! so external routers (Not Diamond, Weave, LiteLLM) are registered with -//! the orchestrator at boot. +//! Tauri setup hook before `fleetify_backend::serve` (which gets it in +//! its `ServeOptions`) so external routers (Not Diamond, Weave, LiteLLM) +//! are registered with the orchestrator at boot. //! //! Also re-used by every `routers_*` IPC mutation: after writing config //! plus keychain the IPC handler rebuilds the `RoutingSetup` from disk diff --git a/vite.config.ts b/vite.config.ts index b48c4b2..3d5b002 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -90,9 +90,11 @@ export default defineConfig({ return { port: vitePort, strictPort: true, + // changeOrigin on every entry: the backend answers only requests + // whose Host is its own (127.0.0.1:), WebSockets too. proxy: { "/api": { target: httpTarget, changeOrigin: true }, - "/ws": { target: wsTarget, ws: true }, + "/ws": { target: wsTarget, ws: true, changeOrigin: true }, "/events": { target: httpTarget, changeOrigin: true }, "/healthz": { target: httpTarget, changeOrigin: true }, }, From 79c63f5060570290b13c171db1af9c609be138a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:49:07 +0300 Subject: [PATCH 04/26] feat(shell): give the renderer a per-run backend token MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The shell generates the backend's API token at startup, keeps it in Tauri state and starts the backend with it, so the backend and the renderer share one token per run. The renderer reads it with window.fleetify.getApiToken(), backed by the new backend_api_token command. Like every app command, it is allowed only for the main webview, through the app-commands set. Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- src-tauri/permissions/app-commands.toml | 1 + src-tauri/src/app_commands.rs | 1 + src-tauri/src/lib.rs | 10 +++++++- src-tauri/src/preload.js | 2 ++ src-tauri/src/shell/ipc/mod.rs | 9 +++++++ src/__tests__/preload-api-token.test.ts | 31 +++++++++++++++++++++++++ src/lib/api.ts | 2 ++ 7 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 src/__tests__/preload-api-token.test.ts diff --git a/src-tauri/permissions/app-commands.toml b/src-tauri/permissions/app-commands.toml index dfadd25..8d0c118 100644 --- a/src-tauri/permissions/app-commands.toml +++ b/src-tauri/permissions/app-commands.toml @@ -13,6 +13,7 @@ permissions = [ "allow-auth-userinfo", "allow-auth-get-access-token", "allow-auth-get-state", + "allow-backend-api-token", "allow-config-get", "allow-config-set", "allow-telemetry-get-config", diff --git a/src-tauri/src/app_commands.rs b/src-tauri/src/app_commands.rs index 5ff0a14..e889e8a 100644 --- a/src-tauri/src/app_commands.rs +++ b/src-tauri/src/app_commands.rs @@ -25,6 +25,7 @@ pub const APP_COMMANDS: &[&str] = &[ "auth_userinfo", "auth_get_access_token", "auth_get_state", + "backend_api_token", "config_get", "config_set", "telemetry_get_config", diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 38836e0..551b3cd 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -99,6 +99,7 @@ pub fn run() { shell::ipc::auth_userinfo, shell::ipc::auth_get_access_token, shell::ipc::auth_get_state, + shell::ipc::backend_api_token, shell::ipc::config_get, shell::ipc::config_set, shell::ipc::telemetry_get_config, @@ -324,6 +325,13 @@ pub fn run() { tokio::sync::watch::channel(shell::backend_ready::BackendStart::Pending); shell::backend_ready::track(backend, backend_start_rx.clone()); + // This run's backend API token. The backend task below starts + // the backend with it, and the renderer asks for it with the + // `backend_api_token` command, which can answer as soon as the + // window exists. + let api_token = fleetify_backend::access::ApiToken::generate(); + app.manage(api_token.clone()); + // IPC from the app's origin. capabilities/default.json covers // only local origins (devUrl in dev mode). The origin the window // loads the app from gets the same permissions here, for that @@ -499,7 +507,7 @@ pub fn run() { let opts = fleetify_backend::ServeOptions { static_dir: sd, routing_setup, - api_token: fleetify_backend::access::ApiToken::generate(), + api_token, }; match fleetify_backend::serve(addr, opts).await { Ok(handle) => { diff --git a/src-tauri/src/preload.js b/src-tauri/src/preload.js index 924472c..0e43d69 100644 --- a/src-tauri/src/preload.js +++ b/src-tauri/src/preload.js @@ -44,6 +44,8 @@ document.addEventListener("mousedown", function (e) { return invoke("auth_get_access_token", { force: !!(opts && opts.force) }); }, getState: function () { return invoke("auth_get_state"); }, + // This run's backend API token (the `backend_api_token` command). + getApiToken: function () { return invoke("backend_api_token"); }, onAuthEvent: function (cb) { var unlisten = null; var e = ev(); diff --git a/src-tauri/src/shell/ipc/mod.rs b/src-tauri/src/shell/ipc/mod.rs index 382b74a..b6214fe 100644 --- a/src-tauri/src/shell/ipc/mod.rs +++ b/src-tauri/src/shell/ipc/mod.rs @@ -49,6 +49,15 @@ pub async fn auth_get_state() -> serde_json::Value { auth::get_state().await } +// ── window.fleetify.getApiToken ─────────────────────────────────── +// This run's backend API token: setup (lib.rs) generates it, manages it and +// passes it to the embedded backend. The renderer asks for it here. + +#[tauri::command] +pub fn backend_api_token(token: tauri::State<'_, fleetify_backend::access::ApiToken>) -> String { + token.as_str().to_owned() +} + // ── window.electronAPI.{getConfig,setConfig} ────────────────────── // Persisted under Tauri's per-app data dir (parity with the Electron // `electron-store`-style JSON-on-disk the original used). diff --git a/src/__tests__/preload-api-token.test.ts b/src/__tests__/preload-api-token.test.ts new file mode 100644 index 0000000..2980b4c --- /dev/null +++ b/src/__tests__/preload-api-token.test.ts @@ -0,0 +1,31 @@ +/** + * `window.fleetify.getApiToken()` asks the shell for this run's backend + * token. The name it invokes must be the Rust command's + * (`backend_api_token`, registered in src-tauri/src/lib.rs and allowed in + * src-tauri/permissions/app-commands.toml); a mismatch would only show at + * runtime. Loads the REAL injected preload script, like + * preload-window-drag.test.ts. + */ +import { describe, it, expect, vi } from "vitest"; +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; + +const PRELOAD_SRC = readFileSync( + resolve(process.cwd(), "src-tauri/src/preload.js"), + "utf8", +); + +const invoke = vi.fn((_cmd: string, _args?: unknown) => Promise.resolve("run-token")); +(window as unknown as { __TAURI__: unknown }).__TAURI__ = { + core: { invoke }, + event: { listen: () => Promise.resolve(() => {}) }, +}; + +new Function(PRELOAD_SRC)(); + +describe("preload window.fleetify.getApiToken", () => { + it("invokes backend_api_token and resolves to what it answers", async () => { + await expect(window.fleetify?.getApiToken()).resolves.toBe("run-token"); + expect(invoke).toHaveBeenCalledWith("backend_api_token", {}); + }); +}); diff --git a/src/lib/api.ts b/src/lib/api.ts index 321af87..17cf615 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -11,6 +11,8 @@ declare global { userinfo: () => Promise; getAccessToken: (opts?: { force?: boolean }) => Promise<{ token: string; expiresAt: number } | null>; getState: () => Promise<{ signedIn: boolean; user?: any; noAuth?: boolean }>; + /** This run's backend API token (the shell's `backend_api_token` command). */ + getApiToken: () => Promise; // Renderer → main bridge for the sidebar's "Give Feedback" modal. // The token is attached in main so the renderer never has to // touch it; the response is the {ok, data?, error?} envelope the From 6d7f86043842d3ef84d7a19ee11762b40432f422 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:07:34 +0300 Subject: [PATCH 05/26] test(backend): build the access tests' client in the shared helper MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TestServer::client() builds the reqwest client the integration tests send their requests with, from one place, with room for headers every request should carry. The access tests use it for every request that isn't sent over raw TCP. Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- crates/fleetify-backend/tests/access.rs | 15 +++++++++++---- crates/fleetify-backend/tests/common/mod.rs | 14 ++++++++++++-- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/crates/fleetify-backend/tests/access.rs b/crates/fleetify-backend/tests/access.rs index fd7d18f..092be26 100644 --- a/crates/fleetify-backend/tests/access.rs +++ b/crates/fleetify-backend/tests/access.rs @@ -22,7 +22,8 @@ async fn start() -> TestServer { /// `GET path` with `host` as the Host header. async fn get_with_host(server: &TestServer, path: &str, host: &str) -> reqwest::Response { - reqwest::Client::new() + server + .client() .get(server.url(path)) .header(reqwest::header::HOST, host) .send() @@ -50,7 +51,12 @@ async fn raw_exchange(addr: SocketAddr, request: &str) -> String { #[tokio::test] async fn healthz_answers_on_its_own_address() { let server = start().await; - let resp = reqwest::get(server.url("/healthz")).await.unwrap(); + let resp = server + .client() + .get(server.url("/healthz")) + .send() + .await + .unwrap(); assert_eq!(resp.status(), 200); } @@ -96,7 +102,8 @@ async fn a_request_without_a_host_is_refused() { #[tokio::test] async fn a_cross_origin_preflight_gets_no_cors_headers() { let server = start().await; - let resp = reqwest::Client::new() + let resp = server + .client() .request(reqwest::Method::OPTIONS, server.url("/api/groups")) .header("Origin", "http://localhost:3000") .header("Access-Control-Request-Method", "POST") @@ -123,7 +130,7 @@ async fn the_ui_files_are_behind_the_host_check() { }) .await; - let served = reqwest::get(server.url("/")).await.unwrap(); + let served = server.client().get(server.url("/")).send().await.unwrap(); assert_eq!(served.status(), 200); assert!(served.text().await.unwrap().contains("FLEET-UI")); diff --git a/crates/fleetify-backend/tests/common/mod.rs b/crates/fleetify-backend/tests/common/mod.rs index b28c8b0..a9e93ef 100644 --- a/crates/fleetify-backend/tests/common/mod.rs +++ b/crates/fleetify-backend/tests/common/mod.rs @@ -1,6 +1,6 @@ //! Shared by the integration tests: the real backend, started with -//! `serve()` on an ephemeral loopback port. A test file pulls it in with -//! `mod common;`. +//! `serve()` on an ephemeral loopback port, and an HTTP client for it. A +//! test file pulls it in with `mod common;`. //! //! It sets no environment variables: each test still sets the ones it needs //! (`FLEET_DB_URL`, `FLEETIFY_NOAUTH`, …) before it starts a server, and the @@ -51,4 +51,14 @@ impl TestServer { pub fn url(&self, path: &str) -> String { format!("http://{}{path}", self.addr()) } + + /// A client for this server. Every request it sends carries + /// `default_headers`, unless the request sets that header itself. + pub fn client(&self) -> reqwest::Client { + let default_headers = reqwest::header::HeaderMap::new(); + reqwest::Client::builder() + .default_headers(default_headers) + .build() + .expect("build the test client") + } } From 4ee5a67b3ec147071a1bb3ce744e3ba325188fb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:28:48 +0300 Subject: [PATCH 06/26] chore(backend): share the test log capture and drop an unused feature MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The access guard's tests and the telemetry client's tests each had a copy of the same tracing capture; they now share one in test_support. tower-http's cors feature has had no user since the CORS layer went away, so the workspace no longer enables it. The access tests also check that the guard's 403 is plain text, and that a cross-origin preflight reaches the router instead of being refused by the guard. Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- Cargo.toml | 2 +- crates/fleetify-backend/src/access.rs | 41 +------------------ .../src/services/telemetry/ws_client.rs | 39 +----------------- crates/fleetify-backend/src/test_support.rs | 41 +++++++++++++++++++ crates/fleetify-backend/tests/access.rs | 16 ++++++++ 5 files changed, 60 insertions(+), 79 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 432033a..f7adeea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ fleetify-core = { path = "crates/fleetify-core" } fleetify-backend = { path = "crates/fleetify-backend" } tokio = { version = "1", features = ["full"] } axum = { version = "0.8", features = ["ws"] } -tower-http = { version = "0.6", features = ["fs", "cors", "trace"] } +tower-http = { version = "0.6", features = ["fs", "trace"] } serde = { version = "1", features = ["derive"] } serde_json = "1" thiserror = "2" diff --git a/crates/fleetify-backend/src/access.rs b/crates/fleetify-backend/src/access.rs index 2a55685..72c2152 100644 --- a/crates/fleetify-backend/src/access.rs +++ b/crates/fleetify-backend/src/access.rs @@ -128,8 +128,6 @@ fn refuse(reason: &'static str, req: &Request) -> Response { #[cfg(test)] mod tests { - use std::sync::Mutex; - use axum::body::Body; use axum::http::Request; use axum::middleware::from_fn_with_state; @@ -138,6 +136,7 @@ mod tests { use tower::ServiceExt; use super::*; + use crate::test_support::LogCapture; #[test] fn the_backends_own_address_is_allowed_in_any_letter_case() { @@ -285,42 +284,4 @@ mod tests { assert!(text.contains(r#"path="/api/x""#), "{text}"); assert!(!text.contains("SECRET"), "the query string was logged"); } - - /// Everything logged on this thread while it lives, as plain text. - struct LogCapture { - lines: Arc>>, - _guard: tracing::subscriber::DefaultGuard, - } - - impl LogCapture { - fn start() -> Self { - let lines = Arc::new(Mutex::new(Vec::new())); - let sink = Arc::clone(&lines); - let subscriber = tracing_subscriber::fmt() - .with_max_level(tracing::Level::TRACE) - .with_ansi(false) - .with_writer(move || CaptureWriter(Arc::clone(&sink))) - .finish(); - Self { - lines, - _guard: tracing::subscriber::set_default(subscriber), - } - } - - fn text(&self) -> String { - String::from_utf8_lossy(&self.lines.lock().unwrap()).into_owned() - } - } - - struct CaptureWriter(Arc>>); - - impl std::io::Write for CaptureWriter { - fn write(&mut self, buf: &[u8]) -> std::io::Result { - self.0.lock().unwrap().extend_from_slice(buf); - Ok(buf.len()) - } - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } - } } diff --git a/crates/fleetify-backend/src/services/telemetry/ws_client.rs b/crates/fleetify-backend/src/services/telemetry/ws_client.rs index 52bb4bf..4a02159 100644 --- a/crates/fleetify-backend/src/services/telemetry/ws_client.rs +++ b/crates/fleetify-backend/src/services/telemetry/ws_client.rs @@ -504,6 +504,7 @@ mod tests { use super::*; use crate::services::telemetry::cloud_gate::test_support::GateGuard; use crate::services::telemetry::set_cloud_enabled; + use crate::test_support::LogCapture; use std::sync::atomic::{AtomicUsize, Ordering}; #[tokio::test] @@ -605,44 +606,6 @@ mod tests { ); } - /// Everything logged on this thread while the guard lives, as plain text. - struct LogCapture { - lines: Arc>>, - _guard: tracing::subscriber::DefaultGuard, - } - - impl LogCapture { - fn start() -> Self { - let lines = Arc::new(std::sync::Mutex::new(Vec::new())); - let sink = Arc::clone(&lines); - let subscriber = tracing_subscriber::fmt() - .with_max_level(tracing::Level::TRACE) - .with_ansi(false) - .with_writer(move || CaptureWriter(Arc::clone(&sink))) - .finish(); - Self { - lines, - _guard: tracing::subscriber::set_default(subscriber), - } - } - - fn text(&self) -> String { - String::from_utf8_lossy(&self.lines.lock().unwrap()).into_owned() - } - } - - struct CaptureWriter(Arc>>); - - impl std::io::Write for CaptureWriter { - fn write(&mut self, buf: &[u8]) -> std::io::Result { - self.0.lock().unwrap().extend_from_slice(buf); - Ok(buf.len()) - } - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } - } - const BEARER: &str = "bearer-0123456789-SECRET-abcdef"; const TICKET: &str = "tkt_0123456789-SECRET-ticket-wxyz"; diff --git a/crates/fleetify-backend/src/test_support.rs b/crates/fleetify-backend/src/test_support.rs index bb3047b..32e2037 100644 --- a/crates/fleetify-backend/src/test_support.rs +++ b/crates/fleetify-backend/src/test_support.rs @@ -2,6 +2,8 @@ //! gating at the call sites, but kept in a regular module so the //! `static` Mutex has a single canonical definition. +use std::sync::{Arc, Mutex}; + /// Mutex tests must hold while mutating `HOME` / `USERPROFILE`. /// Multiple modules' tests touch these env vars; serialising on a /// single static keeps them from racing each other. @@ -9,3 +11,42 @@ pub fn home_lock() -> &'static std::sync::Mutex<()> { static M: std::sync::OnceLock> = std::sync::OnceLock::new(); M.get_or_init(|| std::sync::Mutex::new(())) } + +/// Everything logged on this thread while it lives, as plain text. Tests +/// use it to pin what a log line says, and what it never says. +pub struct LogCapture { + lines: Arc>>, + _guard: tracing::subscriber::DefaultGuard, +} + +impl LogCapture { + pub fn start() -> Self { + let lines = Arc::new(Mutex::new(Vec::new())); + let sink = Arc::clone(&lines); + let subscriber = tracing_subscriber::fmt() + .with_max_level(tracing::Level::TRACE) + .with_ansi(false) + .with_writer(move || CaptureWriter(Arc::clone(&sink))) + .finish(); + Self { + lines, + _guard: tracing::subscriber::set_default(subscriber), + } + } + + pub fn text(&self) -> String { + String::from_utf8_lossy(&self.lines.lock().unwrap()).into_owned() + } +} + +struct CaptureWriter(Arc>>); + +impl std::io::Write for CaptureWriter { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} diff --git a/crates/fleetify-backend/tests/access.rs b/crates/fleetify-backend/tests/access.rs index 092be26..849f24a 100644 --- a/crates/fleetify-backend/tests/access.rs +++ b/crates/fleetify-backend/tests/access.rs @@ -31,6 +31,19 @@ async fn get_with_host(server: &TestServer, path: &str, host: &str) -> reqwest:: .unwrap() } +/// The response's body is plain text, as the guard's 403 is. +fn assert_plain_text(resp: &reqwest::Response) { + let content_type = resp + .headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .unwrap_or_default(); + assert!( + content_type.starts_with("text/plain"), + "content-type: {content_type:?}" + ); +} + /// Send `request` over a plain TCP connection and return the raw response. async fn raw_exchange(addr: SocketAddr, request: &str) -> String { use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -67,6 +80,7 @@ async fn another_host_gets_a_plain_text_403_on_every_path() { let resp = get_with_host(&server, "/healthz", &evil).await; assert_eq!(resp.status(), 403); + assert_plain_text(&resp); assert_eq!(resp.text().await.unwrap(), "forbidden"); // A path no route matches: the 404 is behind the check too. @@ -110,6 +124,8 @@ async fn a_cross_origin_preflight_gets_no_cors_headers() { .send() .await .unwrap(); + // It reached the router: the guard would have answered 403. + assert_ne!(resp.status(), 403, "the guard refused the preflight"); assert!( resp.headers().get("access-control-allow-origin").is_none(), "CORS headers sent: {:?}", From d420f795fd2fde3cdd2872a3604dbdec19272ae2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:36:10 +0300 Subject: [PATCH 07/26] fix(app): send the per-run token on every backend request MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The renderer asks the shell for this run's backend token once and sends it with every request to the backend. Fetches carry it in the X-Fleetify-Token header; WebSocket and EventSource URLs, which can't set a header, carry it as the api_token query parameter. apiFetch adds it next to the access token. The new backendFetch sends only the token, for the routes that don't check who is signed in, and the call sites that used a bare fetch now use one of the two. Renaming, pinning and reordering agents go through apiFetch, since their route checks the access token. The status stream and the Browser panel's URL socket open once the token is in hand, and not after their effect has been cleaned up. A source scan in the tests keeps bare backend fetches, and sockets or streams without the token, from coming back. Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- src/components/chat/message-content.tsx | 4 +- src/components/layout/app-shell.tsx | 14 +- .../layout/session-context-menu.tsx | 3 +- src/components/layout/sidebar.tsx | 6 +- src/components/settings/agents-section.tsx | 3 +- .../workspace/views/browser-view.tsx | 46 +++-- src/components/workspace/workspace-panel.tsx | 23 ++- src/lib/__tests__/api-token.test.ts | 173 ++++++++++++++++++ .../__tests__/no-raw-backend-fetch.test.ts | 81 ++++++++ src/lib/api-token.ts | 57 ++++++ src/lib/api.ts | 48 +++-- 11 files changed, 404 insertions(+), 54 deletions(-) create mode 100644 src/lib/__tests__/api-token.test.ts create mode 100644 src/lib/__tests__/no-raw-backend-fetch.test.ts create mode 100644 src/lib/api-token.ts diff --git a/src/components/chat/message-content.tsx b/src/components/chat/message-content.tsx index 4111a49..efd9194 100644 --- a/src/components/chat/message-content.tsx +++ b/src/components/chat/message-content.tsx @@ -17,7 +17,7 @@ import { SpawnFormCard } from "./spawn-form-card"; import { ChatError } from "./chat-error"; import { LogoMark } from "@/components/brand/logo-mark"; import { ChevronRight, Copy, Check, ArrowRightLeft, CheckCircle2, AlertCircle, Terminal, FileText, Globe, Search, Cpu, CheckSquare, FolderSearch, Pencil, Wrench, Brain, MoveHorizontal, Trash2, FolderOpen, Download, Code2, BarChart2, BookOpen, Image, CornerDownLeft, Send, Bookmark, BookmarkCheck, RotateCcw, X, Clock, ArrowUp, Database } from "lucide-react"; -import { createSessionMemory } from "@/lib/api"; +import { createSessionMemory, backendFetch } from "@/lib/api"; import { formatShortcut } from "@/lib/keyboard-shortcuts"; import { useState, useEffect, useCallback, useRef, useMemo } from "react"; import { claimEscape } from "@/hooks/use-escape-to-stop"; @@ -611,7 +611,7 @@ function ReadFilePreview({ filePath }: { filePath: string }) { const [failed, setFailed] = useState(false); useEffect(() => { let cancelled = false; - fetch(`/api/fs/file?path=${encodeURIComponent(filePath)}`) + backendFetch(`/api/fs/file?path=${encodeURIComponent(filePath)}`) .then((r) => r.json()) .then((j: { content?: string; error?: string }) => { if (cancelled) return; diff --git a/src/components/layout/app-shell.tsx b/src/components/layout/app-shell.tsx index 77c2468..ed14f5f 100644 --- a/src/components/layout/app-shell.tsx +++ b/src/components/layout/app-shell.tsx @@ -27,6 +27,7 @@ import { useDiscoveredModelsStore } from "@/stores/discovered-models-store"; import { providers } from "@/lib/providers-api"; import { useKeyboardShortcuts } from "@/hooks/use-keyboard-shortcuts"; import { fetchSessions, deleteEmptyDrafts, updateSession as apiUpdateSession } from "@/lib/api"; +import { withApiTokenQuery } from "@/lib/api-token"; import type { Session, SessionStatus } from "@/types/session"; // Clamp bounds for the shared sidebar width (the value itself lives in @@ -350,15 +351,20 @@ export function AppShell({ introReveal = false }: { introReveal?: boolean }) { // freeze: a session that finished mid-blip stays "running" in the // sidebar until the user reloads. We restart the connection ourselves // on error with a small backoff so the indicators recover. + // + // The URL carries the API token, which takes an await; `cancelled` is + // checked after it so no stream opens once the effect is cleaned up. const sseRef = useRef(null); useEffect(() => { let cancelled = false; let backoffMs = 1000; let reconnectTimer: ReturnType | null = null; - const open = () => { + const open = async () => { + if (cancelled) return; + const url = await withApiTokenQuery("/events/status"); if (cancelled) return; - const es = new EventSource("/events/status"); + const es = new EventSource(url); sseRef.current = es; es.onopen = () => { backoffMs = 1000; }; // reset on success es.onmessage = (event) => { @@ -376,11 +382,11 @@ export function AppShell({ introReveal = false }: { introReveal?: boolean }) { if (sseRef.current === es) sseRef.current = null; if (cancelled) return; if (reconnectTimer) clearTimeout(reconnectTimer); - reconnectTimer = setTimeout(open, backoffMs); + reconnectTimer = setTimeout(() => { void open(); }, backoffMs); backoffMs = Math.min(backoffMs * 2, 30_000); }; }; - open(); + void open(); return () => { cancelled = true; diff --git a/src/components/layout/session-context-menu.tsx b/src/components/layout/session-context-menu.tsx index affe431..3e8c976 100644 --- a/src/components/layout/session-context-menu.tsx +++ b/src/components/layout/session-context-menu.tsx @@ -13,6 +13,7 @@ import { useAppStore } from "@/stores/app-store"; import { useChatStore } from "@/stores/chat-store"; import { exportChat } from "@/lib/export-chat"; +import { apiFetch } from "@/lib/api"; import { Pin, PinOff, Type, GitFork, Download, Square, RotateCcw, RefreshCw, Trash2, MessageSquare, @@ -70,7 +71,7 @@ export function SessionContextMenu({ x, y, menuRef, session, onClose, onOpen, on const doRename = () => { const n = prompt("Rename:", session.title); if (n) { - fetch(`/api/sessions/${session.id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title: n }) }) + apiFetch(`/api/sessions/${session.id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title: n }) }) .then(() => updateSession(session.id, { title: n })); } }; diff --git a/src/components/layout/sidebar.tsx b/src/components/layout/sidebar.tsx index 6ee9615..ec21e55 100644 --- a/src/components/layout/sidebar.tsx +++ b/src/components/layout/sidebar.tsx @@ -12,7 +12,7 @@ import { ProviderLogo } from "@/components/ui/provider-logo"; import { useChatStore } from "@/stores/chat-store"; import { useShallow } from "zustand/react/shallow"; import { SessionContextMenu } from "@/components/layout/session-context-menu"; -import { forkSession, fetchBulkStats, stopSession, restartSession, resetSession, deleteSession } from "@/lib/api"; +import { forkSession, fetchBulkStats, stopSession, restartSession, resetSession, deleteSession, apiFetch } from "@/lib/api"; import { ConfirmDialog } from "@/components/ui/confirm-dialog"; import { usesInAppTitleBar, folderName } from "@/lib/utils"; import { canDropOn, planSessionDrop } from "@/lib/sidebar-dnd"; @@ -712,7 +712,7 @@ export function Sidebar() { const handlePin = useCallback(async (session: Session) => { const p = !session.pinned; - await fetch(`/api/sessions/${session.id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pinned: p }) }); + await apiFetch(`/api/sessions/${session.id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pinned: p }) }); updateSession(session.id, { pinned: p }); }, [updateSession]); @@ -799,7 +799,7 @@ export function Sidebar() { next.forEach((id, i) => updateSession(id, { order_idx: i } as Partial)); Promise.allSettled( next.map((id, i) => - fetch(`/api/sessions/${id}`, { + apiFetch(`/api/sessions/${id}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ order_idx: i }), diff --git a/src/components/settings/agents-section.tsx b/src/components/settings/agents-section.tsx index 7ed874d..4101bda 100644 --- a/src/components/settings/agents-section.tsx +++ b/src/components/settings/agents-section.tsx @@ -1,6 +1,7 @@ import { useEffect, useRef, useState } from "react"; import { Loader2 } from "lucide-react"; import { useProvidersConfig } from "@/hooks/use-providers-config"; +import { backendFetch } from "@/lib/api"; import { AgentCard, type AgentScanEntry } from "./agents/agent-card"; const sectionHeader: React.CSSProperties = { @@ -16,7 +17,7 @@ const sectionHeader: React.CSSProperties = { async function fetchAgentScan(refresh: boolean): Promise> { try { - const r = await fetch(`/api/agents/scan${refresh ? "?refresh=1" : ""}`, { + const r = await backendFetch(`/api/agents/scan${refresh ? "?refresh=1" : ""}`, { credentials: "include", }); if (!r.ok) return {}; diff --git a/src/components/workspace/views/browser-view.tsx b/src/components/workspace/views/browser-view.tsx index f55117b..fb8f41d 100644 --- a/src/components/workspace/views/browser-view.tsx +++ b/src/components/workspace/views/browser-view.tsx @@ -20,6 +20,7 @@ import { SELECT_MODES, copyTextSafe, parsePickPayload, parseSelectMode, pickToRefDetail, selectModeLabel, selectModeMenuLabel, type SelectMode, } from "@/lib/element-ref"; +import { withApiTokenQuery } from "@/lib/api-token"; import { useAppStore } from "@/stores/app-store"; /* ── Browser pane ── @@ -211,25 +212,36 @@ function BrowserView() { }, []); // Agent CDP → panel: mirror the backend browser's URL into the native webview. + // The URL carries the API token, which takes an await: `closed` keeps a + // socket from opening once the effect is cleaned up. useEffect(() => { + let closed = false; let ws: WebSocket | null = null; - try { - const proto = location.protocol === "https:" ? "wss:" : "ws:"; - ws = new WebSocket(`${proto}//${location.host}/ws/browser-url`); - mirrorWsRef.current = ws; - ws.onmessage = (ev) => { - try { - const m = JSON.parse(typeof ev.data === "string" ? ev.data : "") as { type?: string; url?: string }; - if (m.type === "url" && typeof m.url === "string" && m.url && m.url !== lastMirror.current) { - lastMirror.current = m.url; - setEditUrl(m.url); - openOrNavigate(m.url); - } - } catch { /* ignore */ } - }; - ws.onclose = () => { if (mirrorWsRef.current === ws) mirrorWsRef.current = null; }; - } catch { /* no mirroring */ } - return () => { ws?.close(); if (mirrorWsRef.current === ws) mirrorWsRef.current = null; }; + const proto = location.protocol === "https:" ? "wss:" : "ws:"; + void withApiTokenQuery(`${proto}//${location.host}/ws/browser-url`).then((url) => { + if (closed) return; + try { + const socket = new WebSocket(url); + ws = socket; + mirrorWsRef.current = socket; + socket.onmessage = (ev) => { + try { + const m = JSON.parse(typeof ev.data === "string" ? ev.data : "") as { type?: string; url?: string }; + if (m.type === "url" && typeof m.url === "string" && m.url && m.url !== lastMirror.current) { + lastMirror.current = m.url; + setEditUrl(m.url); + openOrNavigate(m.url); + } + } catch { /* ignore */ } + }; + socket.onclose = () => { if (mirrorWsRef.current === socket) mirrorWsRef.current = null; }; + } catch { /* no mirroring */ } + }); + return () => { + closed = true; + ws?.close(); + if (mirrorWsRef.current === ws) mirrorWsRef.current = null; + }; }, [openOrNavigate]); // Page titles arrive separately (content script → meta channel) — fold them diff --git a/src/components/workspace/workspace-panel.tsx b/src/components/workspace/workspace-panel.tsx index 1c0d44a..61ee50a 100644 --- a/src/components/workspace/workspace-panel.tsx +++ b/src/components/workspace/workspace-panel.tsx @@ -23,9 +23,10 @@ import { BrowserView } from "@/components/workspace/views/browser-view"; import { MONO, SANS } from "@/components/workspace/typography"; import { fetchSessionMemory, createSessionMemory, deleteSessionMemory, - fetchMessages, + fetchMessages, backendFetch, type SessionMemoryItem, } from "@/lib/api"; +import { withApiTokenQuery } from "@/lib/api-token"; import { XtermShell } from "@/components/workspace/xterm-shell"; import { useChatStore, selectSession, type ProcessEvent } from "@/stores/chat-store"; import { usePinnedSession } from "@/lib/session-pins"; @@ -62,7 +63,7 @@ type GitStatus = "M" | "U" | "A" | "D" | null; /* ─── API ─── */ async function apiDir(p: string): Promise { - try { const r = await fetch(`/api/fs/dir?path=${encodeURIComponent(p)}`); return r.ok ? r.json() : []; } catch { return []; } + try { const r = await backendFetch(`/api/fs/dir?path=${encodeURIComponent(p)}`); return r.ok ? r.json() : []; } catch { return []; } } /* Folders first, alphabetical within each kind. Mirrors VS Code's @@ -91,10 +92,10 @@ function entriesEqual(a: FsEntry[] | null, b: FsEntry[]): boolean { return true; } async function apiFile(p: string): Promise<{ content?: string; error?: string }> { - try { const r = await fetch(`/api/fs/file?path=${encodeURIComponent(p)}`); return r.ok ? r.json() : { error: "Failed" }; } catch { return { error: "Failed" }; } + try { const r = await backendFetch(`/api/fs/file?path=${encodeURIComponent(p)}`); return r.ok ? r.json() : { error: "Failed" }; } catch { return { error: "Failed" }; } } async function apiGit(p: string): Promise { - try { const r = await fetch(`/api/fs/git?path=${encodeURIComponent(p)}`); return r.ok ? r.json() : {}; } catch { return {}; } + try { const r = await backendFetch(`/api/fs/git?path=${encodeURIComponent(p)}`); return r.ok ? r.json() : {}; } catch { return {}; } } type DiffScope = "auto" | "working" | "branch"; type DiffResult = { @@ -109,18 +110,18 @@ async function apiGitDiff(p: string, file?: string, scope: DiffScope = "auto"): const params = new URLSearchParams({ path: p }); if (file) params.set("file", file); if (scope !== "auto") params.set("scope", scope); - const r = await fetch(`/api/fs/git/diff?${params.toString()}`); + const r = await backendFetch(`/api/fs/git/diff?${params.toString()}`); return r.ok ? r.json() : { error: "Failed" }; } catch { return { error: "Failed" }; } } async function apiCreate(path: string, type: "file" | "folder"): Promise { - try { const r = await fetch("/api/fs/create", { method:"POST", headers:{"Content-Type":"application/json"}, body: JSON.stringify({ path, type }) }); return r.ok; } catch { return false; } + try { const r = await backendFetch("/api/fs/create", { method:"POST", headers:{"Content-Type":"application/json"}, body: JSON.stringify({ path, type }) }); return r.ok; } catch { return false; } } async function apiDelete(path: string): Promise { - try { const r = await fetch(`/api/fs/delete?path=${encodeURIComponent(path)}`, { method:"DELETE" }); return r.ok; } catch { return false; } + try { const r = await backendFetch(`/api/fs/delete?path=${encodeURIComponent(path)}`, { method:"DELETE" }); return r.ok; } catch { return false; } } async function apiRename(path: string, name: string): Promise<{ ok: boolean; path?: string }> { - try { const r = await fetch("/api/fs/rename", { method:"POST", headers:{"Content-Type":"application/json"}, body: JSON.stringify({ path, name }) }); return r.ok ? r.json() : { ok: false }; } catch { return { ok: false }; } + try { const r = await backendFetch("/api/fs/rename", { method:"POST", headers:{"Content-Type":"application/json"}, body: JSON.stringify({ path, name }) }); return r.ok ? r.json() : { ok: false }; } catch { return { ok: false }; } } /* ─── Context Menu ─── */ @@ -552,7 +553,7 @@ export function FileTree({ root, selectedPath, onSelect }: { /* ─── Save API ─── */ async function apiSave(path: string, content: string): Promise { try { - const r = await fetch("/api/fs/file", { + const r = await backendFetch("/api/fs/file", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ path, content }), @@ -1072,7 +1073,9 @@ function TerminalPanel({ cwd, termKey }: { cwd: string; termKey: string }) { term.open(termRef.current!); fit.fit(); const proto = window.location.protocol === "https:" ? "wss:" : "ws:"; - const ws = new WebSocket(`${proto}//${window.location.host}/ws/terminal?cwd=${encodeURIComponent(cwd)}`); + const ws = new WebSocket( + await withApiTokenQuery(`${proto}//${window.location.host}/ws/terminal?cwd=${encodeURIComponent(cwd)}`), + ); ws.onopen = () => term.focus(); ws.onmessage = e => term.write(e.data); ws.onerror = () => term.writeln("\r\n\x1b[33m⚠ Terminal unavailable\x1b[0m"); diff --git a/src/lib/__tests__/api-token.test.ts b/src/lib/__tests__/api-token.test.ts new file mode 100644 index 0000000..14d75aa --- /dev/null +++ b/src/lib/__tests__/api-token.test.ts @@ -0,0 +1,173 @@ +/** + * The backend's per-run API token on the renderer side: it is asked of the + * shell once (`window.fleetify.getApiToken`), then rides on every backend + * request — the `X-Fleetify-Token` header on fetches, the `api_token` query + * parameter on WebSocket URLs, which can't carry a header. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + API_TOKEN_HEADER, + API_TOKEN_QUERY, + apiToken, + resetApiTokenForTests, + withApiToken, + withApiTokenQuery, +} from "@/lib/api-token"; +import { apiFetch, backendFetch, createSessionsWebSocket } from "@/lib/api"; + +type Bridge = NonNullable; + +/** Install a `window.fleetify` with only the calls a test needs. */ +function bridge(calls: Partial): void { + (window as { fleetify?: Partial }).fleetify = calls; +} + +/** A stubbed fetch that answers every request with `status`. */ +function fetchAnswering(status: number) { + return vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => + new Response(status === 200 ? "{}" : "", { status })); +} + +/** The headers of the `n`-th call to a stubbed fetch. */ +function headersOf(fetchMock: ReturnType, n = 0): Headers { + return new Headers(fetchMock.mock.calls[n]?.[1]?.headers); +} + +beforeEach(() => { + resetApiTokenForTests(); + delete (window as { fleetify?: unknown }).fleetify; +}); + +afterEach(() => { + vi.unstubAllGlobals(); + delete (window as { fleetify?: unknown }).fleetify; +}); + +describe("apiToken", () => { + it("asks the shell once, however many callers wait for it", async () => { + const getApiToken = vi.fn(async () => "run-token"); + bridge({ getApiToken }); + + const tokens = await Promise.all([apiToken(), apiToken(), apiToken()]); + + expect(tokens).toEqual(["run-token", "run-token", "run-token"]); + expect(getApiToken).toHaveBeenCalledTimes(1); + await apiToken(); + expect(getApiToken).toHaveBeenCalledTimes(1); + }); + + it("is null without the Tauri bridge", async () => { + await expect(apiToken()).resolves.toBeNull(); + }); + + it("asks again after a failed ask instead of keeping the failure", async () => { + const getApiToken = vi + .fn<() => Promise>() + .mockRejectedValueOnce(new Error("ipc down")) + .mockResolvedValueOnce("run-token"); + bridge({ getApiToken }); + + await expect(apiToken()).resolves.toBeNull(); + await expect(apiToken()).resolves.toBe("run-token"); + expect(getApiToken).toHaveBeenCalledTimes(2); + }); +}); + +describe("withApiToken", () => { + it("adds the token header and keeps the headers already there", async () => { + bridge({ getApiToken: async () => "run-token" }); + + const init = await withApiToken({ method: "POST", headers: { A: "1" } }); + const headers = new Headers(init.headers); + + expect(init.method).toBe("POST"); + expect(headers.get("A")).toBe("1"); + expect(headers.get(API_TOKEN_HEADER)).toBe("run-token"); + }); + + it("adds nothing without the Tauri bridge", async () => { + const init = await withApiToken({ headers: { A: "1" } }); + const headers = new Headers(init.headers); + + expect(headers.get("A")).toBe("1"); + expect(headers.has(API_TOKEN_HEADER)).toBe(false); + }); +}); + +describe("withApiTokenQuery", () => { + it("appends the token with ? or &, URL-encoded", async () => { + bridge({ getApiToken: async () => "a b/c+d&e" }); + const encoded = "a%20b%2Fc%2Bd%26e"; + + await expect(withApiTokenQuery("/ws/x")).resolves.toBe(`/ws/x?${API_TOKEN_QUERY}=${encoded}`); + await expect(withApiTokenQuery("/ws/x?token=j")).resolves.toBe( + `/ws/x?token=j&${API_TOKEN_QUERY}=${encoded}`, + ); + }); + + it("leaves the URL alone without the Tauri bridge", async () => { + await expect(withApiTokenQuery("/ws/x?token=j")).resolves.toBe("/ws/x?token=j"); + }); +}); + +describe("the backend requests in api.ts", () => { + it("apiFetch sends both the access token and the API token", async () => { + bridge({ + getApiToken: async () => "run-token", + getAccessToken: async () => ({ token: "jwt", expiresAt: 0 }), + }); + const fetchMock = fetchAnswering(200); + vi.stubGlobal("fetch", fetchMock); + + await apiFetch("/api/sessions", { headers: { "Content-Type": "application/json" } }); + + const headers = headersOf(fetchMock); + expect(headers.get("Authorization")).toBe("Bearer jwt"); + expect(headers.get(API_TOKEN_HEADER)).toBe("run-token"); + expect(headers.get("Content-Type")).toBe("application/json"); + }); + + it("backendFetch sends only the API token, and a 401 doesn't sign out", async () => { + const signOut = vi.fn(async () => ({ ok: true })); + const getAccessToken = vi.fn(async () => ({ token: "jwt", expiresAt: 0 })); + bridge({ getApiToken: async () => "run-token", getAccessToken, signOut }); + const fetchMock = fetchAnswering(401); + vi.stubGlobal("fetch", fetchMock); + + const res = await backendFetch("/api/fs/dir?path=%2Ftmp"); + + expect(res.status).toBe(401); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock.mock.calls[0]?.[0]).toBe("/api/fs/dir?path=%2Ftmp"); + const headers = headersOf(fetchMock); + expect(headers.get(API_TOKEN_HEADER)).toBe("run-token"); + expect(headers.has("Authorization")).toBe(false); + expect(getAccessToken).not.toHaveBeenCalled(); + expect(signOut).not.toHaveBeenCalled(); + }); + + it("the sessions socket URL carries the access token and the API token", async () => { + bridge({ + getApiToken: async () => "run-token", + getAccessToken: async () => ({ token: "jwt", expiresAt: 0 }), + }); + const urls: string[] = []; + vi.stubGlobal( + "WebSocket", + class { + constructor(url: string) { + urls.push(url); + } + }, + ); + + await createSessionsWebSocket(); + + expect(urls).toHaveLength(1); + const url = urls[0] ?? ""; + expect(url).toContain("/ws/sessions?"); + const query = new URLSearchParams(url.slice(url.indexOf("?") + 1)); + expect(query.get("token")).toBe("jwt"); + expect(query.get(API_TOKEN_QUERY)).toBe("run-token"); + }); +}); diff --git a/src/lib/__tests__/no-raw-backend-fetch.test.ts b/src/lib/__tests__/no-raw-backend-fetch.test.ts new file mode 100644 index 0000000..281a6a4 --- /dev/null +++ b/src/lib/__tests__/no-raw-backend-fetch.test.ts @@ -0,0 +1,81 @@ +/** + * Every renderer request to the backend carries the per-run API token, so + * none may go out through a bare `fetch` or open a socket or stream without + * the token in its URL. This scans the renderer's own sources: + * - no `fetch(` whose first argument is a backend path (`/api…`, + * `${API_BASE}…`, `/events…`): those go through `apiFetch` (JWT routes) + * or `backendFetch`; + * - every file that opens a `WebSocket` or `EventSource` also calls + * `withApiTokenQuery`. + * Tests are skipped, and so are `api.ts` and `api-token.ts`, which define the + * helpers; `api.ts`'s socket builders are covered by api-token.test.ts. + */ +import { readdirSync, readFileSync } from "node:fs"; +import { join, resolve, sep } from "node:path"; +import { describe, expect, it } from "vitest"; + +const SRC = resolve(__dirname, "../.."); +const HELPERS = new Set(["lib/api.ts", "lib/api-token.ts"]); + +/** A bare `fetch(` (also `window.fetch(`) whose first argument is a backend path. */ +const RAW_BACKEND_FETCH = /(? file.split(sep).join("/")) + .filter((file) => /\.tsx?$/.test(file)) + .filter((file) => !file.split("/").includes("__tests__") && !/\.test\.tsx?$/.test(file)) + .filter((file) => !HELPERS.has(file)) + .map((file) => ({ file, text: readFileSync(join(SRC, file), "utf8") })); +} + +/** `file:line` for each bare backend fetch in `text`. */ +function rawFetches(file: string, text: string): string[] { + return [...text.matchAll(RAW_BACKEND_FETCH)].map( + (m) => `${file}:${text.slice(0, m.index).split("\n").length}`, + ); +} + +describe("backend requests carry the API token", () => { + it("the fetch pattern catches bare backend fetches and nothing else", () => { + const caught = [ + 'fetch("/api/fs/dir")', + "fetch('/api/groups')", + "fetch(`/api/sessions/${id}`, { method: \"PATCH\" })", + "fetch(`${API_BASE}/groups`)", + 'fetch("/events/status")', + 'await window.fetch("/api/x")', + 'fetch(\n "/api/fs/file",\n { method: "PUT" })', + ]; + const ignored = [ + 'apiFetch("/api/sessions")', + 'backendFetch("/api/fs/dir")', + 'fetch("https://example.com/api/x")', + "fetch(url)", + "const fetch = useCallback(() => {}, []); fetch();", + ]; + for (const text of caught) expect(rawFetches("x.ts", text), text).toHaveLength(1); + for (const text of ignored) expect(rawFetches("x.ts", text), text).toEqual([]); + }); + + it("scans the renderer's sources", () => { + const files = sources().map((s) => s.file); + expect(files.length).toBeGreaterThan(100); + expect(files).toContain("components/workspace/workspace-panel.tsx"); + expect(files).not.toContain("lib/api.ts"); + }); + + it("no source fetches a backend path without apiFetch or backendFetch", () => { + const offenders = sources().flatMap(({ file, text }) => rawFetches(file, text)); + expect(offenders).toEqual([]); + }); + + it("every file that opens a WebSocket or EventSource adds the token to its URL", () => { + const offenders = sources() + .filter(({ text }) => OPENS_SOCKET_OR_STREAM.test(text) && !text.includes("withApiTokenQuery(")) + .map(({ file }) => file); + expect(offenders).toEqual([]); + }); +}); diff --git a/src/lib/api-token.ts b/src/lib/api-token.ts new file mode 100644 index 0000000..e1b3a92 --- /dev/null +++ b/src/lib/api-token.ts @@ -0,0 +1,57 @@ +/** + * The backend's per-run API token. The shell makes it at startup and gives it + * to the renderer over IPC (`window.fleetify.getApiToken`, the + * `backend_api_token` command). Every request to the backend carries it: + * fetches in the `X-Fleetify-Token` header (through `apiFetch` / + * `backendFetch` in api.ts), and WebSocket / EventSource URLs, which can't + * set a header, in the `api_token` query parameter (`withApiTokenQuery`). + */ + +export const API_TOKEN_HEADER = "X-Fleetify-Token"; +export const API_TOKEN_QUERY = "api_token"; + +let asked: Promise | null = null; + +/** Fetched once over IPC (window.fleetify.getApiToken) and memoised; null when there is no Tauri bridge + * (a plain-browser dev run with FLEETIFY_NOAUTH=1, where the backend doesn't ask for it). + * A failed ask resolves to null and is not memoised, so the next call asks again. */ +export function apiToken(): Promise { + const bridge = typeof window === "undefined" ? undefined : window.fleetify; + if (!bridge || typeof bridge.getApiToken !== "function") return Promise.resolve(null); + if (!asked) { + const ask: Promise = Promise.resolve() + .then(() => bridge.getApiToken()) + .then((token) => (typeof token === "string" && token !== "" ? token : null)) + .catch(() => null); + asked = ask; + void ask.then((token) => { + if (token === null && asked === ask) asked = null; + }); + } + return asked; +} + +/** `init` plus the token header; the headers already in `init` stay. */ +export async function withApiToken(init: RequestInit = {}): Promise { + const token = await apiToken(); + if (token === null) return init; + const headers = new Headers(init.headers); + headers.set(API_TOKEN_HEADER, token); + return { ...init, headers }; +} + +/** `url` plus `api_token=`, after `?` or `&` as the URL needs. */ +export async function withApiTokenQuery(url: string): Promise { + const token = await apiToken(); + if (token === null) return url; + const hashAt = url.indexOf("#"); + const base = hashAt === -1 ? url : url.slice(0, hashAt); + const hash = hashAt === -1 ? "" : url.slice(hashAt); + const separator = !base.includes("?") ? "?" : /[?&]$/.test(base) ? "" : "&"; + return `${base}${separator}${API_TOKEN_QUERY}=${encodeURIComponent(token)}${hash}`; +} + +/** Forget the memoised token, so each test starts from the shell again. */ +export function resetApiTokenForTests(): void { + asked = null; +} diff --git a/src/lib/api.ts b/src/lib/api.ts index 17cf615..4d41376 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -1,4 +1,5 @@ import type { EffortCapability } from "@/lib/providers-api"; +import { withApiToken, withApiTokenQuery } from "@/lib/api-token"; const API_BASE = "/api"; @@ -74,13 +75,19 @@ async function authHeaders(): Promise> { * retries once. A second 401 ends the session: we sign out via the * main process and dispatch fleet:logout so App.tsx can route back to * the sign-in screen. Exported so other modules (plugin-api, mcp-api, - * WorkflowsPage, etc.) share the same retry + sign-out semantics. */ + * WorkflowsPage, etc.) share the same retry + sign-out semantics. + * Every request also carries the backend's per-run API token. */ export async function apiFetch(input: RequestInfo, init?: RequestInit): Promise { - const baseHeaders = (init?.headers ?? {}) as Record; - let res = await fetch(input, { ...init, headers: { ...baseHeaders, ...(await authHeaders()) } }); + const send = async () => { + const withToken = await withApiToken(init); + const headers = new Headers(withToken.headers); + for (const [name, value] of Object.entries(await authHeaders())) headers.set(name, value); + return fetch(input, { ...withToken, headers }); + }; + let res = await send(); if (res.status === 401) { await window.fleetify?.getAccessToken({ force: true }); - res = await fetch(input, { ...init, headers: { ...baseHeaders, ...(await authHeaders()) } }); + res = await send(); if (res.status === 401) { await window.fleetify?.signOut(); window.dispatchEvent(new Event("fleet:logout")); @@ -90,6 +97,14 @@ export async function apiFetch(input: RequestInfo, init?: RequestInit): Promise< return res; } +/** A backend request that needs only the per-run API token: routes that + * take no access token (the workspace file API, the folder picker, the + * agent scan, …). No JWT, so no refresh-and-retry and no sign-out on a + * 401; use `apiFetch` for the routes that check who is signed in. */ +export async function backendFetch(input: string, init?: RequestInit): Promise { + return fetch(input, await withApiToken(init)); +} + // ── SSH (Remote tab) ──────────────────────────────────────────── export interface SshTarget { host: string; @@ -763,7 +778,7 @@ export async function dispatchFollowUp( } export async function fetchGroups() { - const res = await fetch(`${API_BASE}/groups`); + const res = await backendFetch(`${API_BASE}/groups`); if (!res.ok) throw new Error("Failed to fetch groups"); return res.json(); } @@ -1051,13 +1066,13 @@ export interface PathValidation { } export async function validatePath(path: string): Promise { - const res = await fetch(`${API_BASE}/fs/validate?path=${encodeURIComponent(path)}`); + const res = await backendFetch(`${API_BASE}/fs/validate?path=${encodeURIComponent(path)}`); if (!res.ok) throw new Error("Failed to validate path"); return res.json(); } export async function fetchDefaultPath(): Promise { - const res = await fetch(`${API_BASE}/fs/default`); + const res = await backendFetch(`${API_BASE}/fs/default`); if (!res.ok) throw new Error("Failed to fetch default path"); const data = (await res.json()) as { path: string }; return data.path; @@ -1065,7 +1080,7 @@ export async function fetchDefaultPath(): Promise { export async function pickFolder(initial?: string): Promise { const qs = initial ? `?initial=${encodeURIComponent(initial)}` : ""; - const res = await fetch(`${API_BASE}/fs/pick${qs}`); + const res = await backendFetch(`${API_BASE}/fs/pick${qs}`); if (!res.ok) throw new Error("Failed to open folder picker"); const data = (await res.json()) as { path: string }; return data.path; @@ -1380,22 +1395,23 @@ export async function analyzeFleetResponse( /** Connect to the shared interactive browser stream. Binary messages are * live JPEG frames (DOWN); JSON text messages are user input (UP) — * `{type:"navigate"|"click"|"scroll"|"type"|"key"|"back"|"forward"|"reload", …}`. - * Unauthenticated (loopback) for now; the page content is just the agent's - * browser viewport. */ -export function createBrowserWebSocket(): WebSocket { + * No access token (loopback); the page content is just the agent's + * browser viewport. The URL carries the per-run API token. */ +export async function createBrowserWebSocket(): Promise { const protocol = window.location.protocol === "https:" ? "wss:" : "ws:"; - return new WebSocket(`${protocol}//${window.location.host}/ws/browser`); + return new WebSocket(await withApiTokenQuery(`${protocol}//${window.location.host}/ws/browser`)); } export async function createChatWebSocket(sessionId: string): Promise { const protocol = window.location.protocol === "https:" ? "wss:" : "ws:"; const host = window.location.host; // WebSocket browsers don't expose a way to send Authorization headers, - // so the JWT rides as a query param. Backend validates + ownership-checks - // before accepting any messages on the socket. + // so the JWT rides as a query param, next to the per-run API token. + // Backend validates + ownership-checks before accepting any messages on + // the socket. const t = await window.fleetify?.getAccessToken(); const qs = t?.token ? `?token=${encodeURIComponent(t.token)}` : ""; - return new WebSocket(`${protocol}//${host}/ws/chat/${sessionId}${qs}`); + return new WebSocket(await withApiTokenQuery(`${protocol}//${host}/ws/chat/${sessionId}${qs}`)); } /** Open the multiplexed sessions socket — ONE physical connection @@ -1420,7 +1436,7 @@ export async function createSessionsWebSocket(): Promise { throw new Error("No access token — sign in required"); } const qs = `?token=${encodeURIComponent(t.token)}`; - return new WebSocket(`${protocol}//${host}/ws/sessions${qs}`); + return new WebSocket(await withApiTokenQuery(`${protocol}//${host}/ws/sessions${qs}`)); } // ── Routing summary (Fleet right sidebar Router section) ────── From 0d6936e2114b42da96ea367837d2318edcad40d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:45:39 +0300 Subject: [PATCH 08/26] fix(backend): require the per-run token on API requests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The access guard now also asks API requests for this run's token. It reads it from the X-Fleetify-Token header. A WebSocket upgrade under /ws/ and GET /events/status may carry it in the api_token query parameter instead, since their URLs can't have a header. A missing, wrong or repeated token gets the same plain-text 403 as a wrong host. No token is needed for /healthz, for GET and HEAD of the UI files, for the /api/internal routes (their handlers check the internal secret) or for the system browser's MCP OAuth callback. Release builds always require the token. A debug build running with FLEETIFY_NOAUTH=1 doesn't, unless FLEETIFY_REQUIRE_API_TOKEN=1 is set; both are read once at startup. The integration tests that sign their own JWTs send the token through the shared test client, which now sets it by default. Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- crates/fleetify-backend/src/access.rs | 561 +++++++++++++++++- crates/fleetify-backend/src/http.rs | 6 +- crates/fleetify-backend/src/lib.rs | 38 +- .../fleetify-backend/src/routers/internal.rs | 7 +- crates/fleetify-backend/tests/access.rs | 166 +++++- crates/fleetify-backend/tests/common/mod.rs | 25 +- crates/fleetify-backend/tests/phase4_apis.rs | 17 +- crates/fleetify-backend/tests/sessions_api.rs | 18 +- crates/fleetify-backend/tests/ws_protocol.rs | 37 +- docs/RUNNING.md | 5 + 10 files changed, 803 insertions(+), 77 deletions(-) diff --git a/crates/fleetify-backend/src/access.rs b/crates/fleetify-backend/src/access.rs index 72c2152..ba69ac2 100644 --- a/crates/fleetify-backend/src/access.rs +++ b/crates/fleetify-backend/src/access.rs @@ -1,22 +1,28 @@ //! Who the embedded backend answers. //! //! The backend listens on `127.0.0.1:` for the app alone: its window, -//! the shell and the agents' helper processes. A request has to be addressed -//! to that host, `127.0.0.1:` or `localhost:`; any other gets a -//! plain-text 403. [`guard`] is the router's outermost layer -//! (`http::app`), so this holds for every path: the API, `/healthz`, the UI -//! files and the 404s. +//! the shell and the agents' helper processes. [`guard`] is the router's +//! outermost layer (`http::app`), so its checks hold for every path: the +//! API, `/healthz`, the UI files and the 404s. [`decide`] has the rules: //! -//! Each run also has an [`ApiToken`]. The shell makes it at startup, passes -//! it to [`crate::serve`] and gives it to the renderer over IPC -//! (`backend_api_token`). +//! - A request has to be addressed to the backend's own host, +//! `127.0.0.1:` or `localhost:`. +//! - An API request also needs this run's [`ApiToken`]. The shell makes it +//! at startup, passes it to [`crate::serve`] and gives it to the renderer +//! over IPC (`backend_api_token`). It travels in the `X-Fleetify-Token` +//! header. A WebSocket upgrade or the status stream, whose URLs the +//! renderer can't give a header, may carry it in the `api_token` query +//! parameter instead. +//! +//! Anything else gets a plain-text 403. +use std::borrow::Cow; use std::fmt; use std::fmt::Write as _; use std::sync::Arc; use axum::extract::{Request, State}; -use axum::http::{header, StatusCode}; +use axum::http::{header, HeaderMap, Method, StatusCode}; use axum::middleware::Next; use axum::response::{IntoResponse, Response}; use rand::RngCore; @@ -27,6 +33,12 @@ pub const API_TOKEN_HEADER: &str = "x-fleetify-token"; /// (WebSocket and EventSource). pub const API_TOKEN_QUERY: &str = "api_token"; +/// The system browser's redirect at the end of an MCP server's OAuth flow. +/// It can't carry the token; the flow's `state` guards it. +const MCP_AUTH_CALLBACK_PATH: &str = "/api/mcp/auth/callback"; +/// The status stream (an `EventSource`). +const STATUS_STREAM_PATH: &str = "/events/status"; + /// This run's API token. Its `Debug` never shows the value. #[derive(Clone)] pub struct ApiToken(Arc); @@ -66,6 +78,99 @@ pub struct AccessPolicy { pub port: u16, /// This run's token. pub token: ApiToken, + /// Whether API requests need the token; see [`token_required`]. + pub token_required: bool, +} + +/// Whether API requests need the token: always in a release build +/// (`release`), and in a debug build unless it runs with `FLEETIFY_NOAUTH=1` +/// (`no_auth`). `force` (`FLEETIFY_REQUIRE_API_TOKEN=1`, which only a debug +/// build reads) asks for it even then. +pub fn token_required(release: bool, no_auth: bool, force: bool) -> bool { + release || !no_auth || force +} + +/// What [`decide`] needs to know about a request. +pub struct RequestFacts<'a> { + pub method: &'a Method, + /// The URI's path, without the query. + pub path: &'a str, + /// The `Host` header, or the URI's authority when there is none. + pub host: Option<&'a str>, + /// The `X-Fleetify-Token` header. + pub header_token: Option<&'a str>, + /// The `api_token` query parameter, percent-decoded. + pub query_token: Option<&'a str>, + /// Whether the request asks to upgrade to a WebSocket. + pub websocket_upgrade: bool, +} + +/// What [`decide`] answers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Verdict { + Allow, + /// Refused, with the reason the log line gives: `"host"` or `"token"`. + Forbidden(&'static str), +} + +/// Whether the backend answers a request. The rules, in order: +/// +/// 1. A request addressed to another host is refused (`"host"`). +/// 2. Without the token requirement, everything else is allowed. +/// 3. These need no token: +/// - `GET`/`HEAD /healthz`; +/// - `GET`/`HEAD` of any path outside `/api/`, `/ws/` and `/events/` (the +/// UI); +/// - any method under `/api/internal/` (the handlers check the internal +/// secret); +/// - `GET /api/mcp/auth/callback`. +/// 4. The token in the header is allowed. +/// 5. The token in the query is allowed on a WebSocket upgrade under `/ws/` +/// and on `GET /events/status`. +/// 6. Everything else is refused (`"token"`). +/// +/// Every token comparison goes through [`ApiToken::matches`]. +pub fn decide(facts: &RequestFacts<'_>, policy: &AccessPolicy) -> Verdict { + if !host_allowed(facts.host, policy.port) { + return Verdict::Forbidden("host"); + } + if !policy.token_required || needs_no_token(facts) { + return Verdict::Allow; + } + if facts + .header_token + .is_some_and(|token| policy.token.matches(token)) + { + return Verdict::Allow; + } + if query_token_counts(facts) + && facts + .query_token + .is_some_and(|token| policy.token.matches(token)) + { + return Verdict::Allow; + } + Verdict::Forbidden("token") +} + +/// Rule 3 of [`decide`]. +fn needs_no_token(facts: &RequestFacts<'_>) -> bool { + let (method, path) = (facts.method, facts.path); + let read = *method == Method::GET || *method == Method::HEAD; + let api = ["/api/", "/ws/", "/events/"] + .iter() + .any(|prefix| path.starts_with(prefix)); + (read && path == crate::HEALTH_PATH) + || (read && !api) + || path.starts_with("/api/internal/") + || (*method == Method::GET && path == MCP_AUTH_CALLBACK_PATH) +} + +/// Rule 5 of [`decide`]: where the query token counts. +fn query_token_counts(facts: &RequestFacts<'_>) -> bool { + *facts.method == Method::GET + && ((facts.websocket_upgrade && facts.path.starts_with("/ws/")) + || facts.path == STATUS_STREAM_PATH) } /// Whether `host`, a request's `Host` (or its URI authority), is the @@ -92,13 +197,25 @@ pub(crate) fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { diff == 0 } -/// The router's outermost layer: a request that isn't addressed to the -/// backend's own host gets a plain-text 403. +/// The router's outermost layer: what [`decide`] refuses gets a plain-text +/// 403, and the rest goes on to the router. pub async fn guard(State(policy): State, req: Request, next: Next) -> Response { - if !host_allowed(request_host(&req), policy.port) { - return refuse("host", &req); + let verdict = { + let query_token = single_query_param(req.uri().query(), API_TOKEN_QUERY); + let facts = RequestFacts { + method: req.method(), + path: req.uri().path(), + host: request_host(&req), + header_token: single_header(req.headers(), API_TOKEN_HEADER), + query_token: query_token.as_deref(), + websocket_upgrade: is_websocket_upgrade(req.headers()), + }; + decide(&facts, &policy) + }; + match verdict { + Verdict::Allow => next.run(req).await, + Verdict::Forbidden(reason) => refuse(reason, &req), } - next.run(req).await } /// The host a request is addressed to: its `Host` header, or the URI's @@ -113,6 +230,44 @@ fn request_host(req: &Request) -> Option<&str> { } } +/// The value of a header the request has exactly once; twice counts as +/// none. +fn single_header<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> { + let mut values = headers.get_all(name).iter(); + match (values.next(), values.next()) { + (Some(value), None) => value.to_str().ok(), + _ => None, + } +} + +/// The percent-decoded value of a query parameter the request has exactly +/// once; twice counts as none. +fn single_query_param<'a>(query: Option<&'a str>, name: &str) -> Option> { + let mut values = url::form_urlencoded::parse(query?.as_bytes()) + .filter(|(key, _)| key == name) + .map(|(_, value)| value); + match (values.next(), values.next()) { + (Some(value), None) => Some(value), + _ => None, + } +} + +/// Whether a request asks to upgrade to a WebSocket: `Upgrade: websocket`, +/// with `upgrade` among its `Connection` options, in any letter case. +fn is_websocket_upgrade(headers: &HeaderMap) -> bool { + let upgrade = headers + .get(header::UPGRADE) + .and_then(|value| value.to_str().ok()) + .is_some_and(|value| value.trim().eq_ignore_ascii_case("websocket")); + let connection = headers + .get_all(header::CONNECTION) + .iter() + .filter_map(|value| value.to_str().ok()) + .flat_map(|value| value.split(',')) + .any(|option| option.trim().eq_ignore_ascii_case("upgrade")); + upgrade && connection +} + /// The 403. The log line has the path without its query string, which can /// carry a token. fn refuse(reason: &'static str, req: &Request) -> Response { @@ -129,7 +284,7 @@ fn refuse(reason: &'static str, req: &Request) -> Response { #[cfg(test)] mod tests { use axum::body::Body; - use axum::http::Request; + use axum::http::{Method, Request}; use axum::middleware::from_fn_with_state; use axum::routing::get; use axum::Router; @@ -210,15 +365,270 @@ mod tests { assert!(constant_time_eq(b"", b"")); } - /// One route behind the guard, for a backend bound to port 8765. - async fn through_guard(req: Request) -> (StatusCode, String) { - let policy = AccessPolicy { + #[test] + fn the_token_is_required_unless_a_debug_build_runs_without_auth() { + // (release, no_auth, force) → required + for (release, no_auth, force, required) in [ + (true, true, false, true), + (false, true, false, false), + (false, false, false, true), + (false, true, true, true), + (true, false, false, true), + (true, true, true, true), + (true, false, true, true), + (false, false, true, true), + ] { + assert_eq!( + token_required(release, no_auth, force), + required, + "release={release} no_auth={no_auth} force={force}" + ); + } + } + + /// A policy for a backend bound to port 8765, with a new token. + fn policy(token_required: bool) -> AccessPolicy { + AccessPolicy { port: 8765, token: ApiToken::generate(), - }; + token_required, + } + } + + /// A request for `path` on the backend's own address, with no token. + fn facts<'a>(method: &'a Method, path: &'a str) -> RequestFacts<'a> { + RequestFacts { + method, + path, + host: Some("127.0.0.1:8765"), + header_token: None, + query_token: None, + websocket_upgrade: false, + } + } + + #[test] + fn decide_applies_its_rules_in_order() { + let policy = policy(true); + let token = policy.token.as_str(); + let other = ApiToken::generate(); + let wrong = other.as_str(); + let (get, head, post) = (Method::GET, Method::HEAD, Method::POST); + const ALLOW: Verdict = Verdict::Allow; + const NO_TOKEN: Verdict = Verdict::Forbidden("token"); + const BAD_HOST: Verdict = Verdict::Forbidden("host"); + let evil = Some("evil.example:8765"); + + let rows = [ + // 1. The host comes first, even with a valid token. + ( + "a bad host, with the header token", + RequestFacts { + host: evil, + header_token: Some(token), + ..facts(&get, "/api/fs/dir") + }, + BAD_HOST, + ), + ( + "a bad host, for a UI file", + RequestFacts { + host: evil, + ..facts(&get, "/") + }, + BAD_HOST, + ), + ( + "no host, for /healthz", + RequestFacts { + host: None, + ..facts(&get, "/healthz") + }, + BAD_HOST, + ), + // 3. What needs no token. + ("HEAD /healthz", facts(&head, "/healthz"), ALLOW), + ("GET /healthz", facts(&get, "/healthz"), ALLOW), + ("GET of the UI", facts(&get, "/"), ALLOW), + ("GET of a UI asset", facts(&get, "/assets/index.js"), ALLOW), + ( + "HEAD of a UI asset", + facts(&head, "/assets/index.js"), + ALLOW, + ), + ( + "an internal route", + facts(&post, "/api/internal/dispatch"), + ALLOW, + ), + ( + "the OAuth callback", + facts(&get, "/api/mcp/auth/callback"), + ALLOW, + ), + ("a POST to the UI", facts(&post, "/"), NO_TOKEN), + ( + "a POST to the OAuth callback", + facts(&post, "/api/mcp/auth/callback"), + NO_TOKEN, + ), + ("HEAD of an API path", facts(&head, "/api/fs/dir"), NO_TOKEN), + // 4. The header token counts everywhere. + ( + "an API path without a token", + facts(&get, "/api/fs/dir"), + NO_TOKEN, + ), + ( + "an API path with the header token", + RequestFacts { + header_token: Some(token), + ..facts(&get, "/api/fs/dir") + }, + ALLOW, + ), + ( + "an API path with a wrong header token", + RequestFacts { + header_token: Some(wrong), + ..facts(&get, "/api/fs/dir") + }, + NO_TOKEN, + ), + ( + "a socket upgrade with the header token", + RequestFacts { + header_token: Some(token), + websocket_upgrade: true, + ..facts(&get, "/ws/sessions") + }, + ALLOW, + ), + // 5. The query token counts on socket upgrades and the status + // stream only. + ( + "an API path with only the query token", + RequestFacts { + query_token: Some(token), + ..facts(&get, "/api/fs/dir") + }, + NO_TOKEN, + ), + ( + "an upgrade on an API path with only the query token", + RequestFacts { + query_token: Some(token), + websocket_upgrade: true, + ..facts(&get, "/api/fs/dir") + }, + NO_TOKEN, + ), + ( + "a socket upgrade with the query token", + RequestFacts { + query_token: Some(token), + websocket_upgrade: true, + ..facts(&get, "/ws/sessions") + }, + ALLOW, + ), + ( + "a socket path with the query token, not upgrading", + RequestFacts { + query_token: Some(token), + ..facts(&get, "/ws/sessions") + }, + NO_TOKEN, + ), + ( + "a POST socket upgrade with the query token", + RequestFacts { + query_token: Some(token), + websocket_upgrade: true, + ..facts(&post, "/ws/sessions") + }, + NO_TOKEN, + ), + ( + "a socket upgrade with a wrong query token", + RequestFacts { + query_token: Some(wrong), + websocket_upgrade: true, + ..facts(&get, "/ws/sessions") + }, + NO_TOKEN, + ), + ( + "the status stream with the query token", + RequestFacts { + query_token: Some(token), + ..facts(&get, "/events/status") + }, + ALLOW, + ), + ( + "the status stream without a token", + facts(&get, "/events/status"), + NO_TOKEN, + ), + ( + "a POST to the status stream with the query token", + RequestFacts { + query_token: Some(token), + ..facts(&post, "/events/status") + }, + NO_TOKEN, + ), + ( + "another stream with the query token", + RequestFacts { + query_token: Some(token), + ..facts(&get, "/events/other") + }, + NO_TOKEN, + ), + // 6. Everything else. + ( + "an unknown API path", + facts(&get, "/api/no-such-route"), + NO_TOKEN, + ), + ]; + for (name, facts, want) in rows { + assert_eq!(decide(&facts, &policy), want, "{name}"); + } + } + + #[test] + fn without_the_token_requirement_only_the_host_is_checked() { + let policy = policy(false); + let (get, post) = (Method::GET, Method::POST); + + assert_eq!(decide(&facts(&get, "/api/fs/dir"), &policy), Verdict::Allow); + assert_eq!( + decide(&facts(&post, "/api/sessions"), &policy), + Verdict::Allow + ); + assert_eq!( + decide( + &RequestFacts { + host: Some("evil.example:8765"), + ..facts(&get, "/api/fs/dir") + }, + &policy + ), + Verdict::Forbidden("host") + ); + } + + /// A few routes behind the guard with `policy`: what it answers. + async fn through(policy: &AccessPolicy, req: Request) -> (StatusCode, String) { + let ok = || async { "ok" }; let app = Router::new() - .route("/api/x", get(|| async { "ok" }).post(|| async { "ok" })) - .layer(from_fn_with_state(policy, guard)); + .route("/api/x", get(ok).post(ok)) + .route("/ws/x", get(ok)) + .route("/events/status", get(ok)) + .layer(from_fn_with_state(policy.clone(), guard)); let resp = app.oneshot(req).await.unwrap(); let status = resp.status(); let body = axum::body::to_bytes(resp.into_body(), usize::MAX) @@ -227,6 +637,11 @@ mod tests { (status, String::from_utf8_lossy(&body).into_owned()) } + /// Through a guard that checks only the host. + async fn through_guard(req: Request) -> (StatusCode, String) { + through(&policy(false), req).await + } + fn request(uri: &str, hosts: &[&str]) -> Request { let mut req = Request::builder().uri(uri); for host in hosts { @@ -235,6 +650,15 @@ mod tests { req.body(Body::empty()).unwrap() } + /// `GET uri` on the backend's own address, with `headers`. + fn get_with(uri: &str, headers: &[(&str, &str)]) -> Request { + let mut req = Request::builder().uri(uri).header("host", "127.0.0.1:8765"); + for (name, value) in headers { + req = req.header(*name, *value); + } + req.body(Body::empty()).unwrap() + } + #[tokio::test] async fn the_guard_checks_the_host_header_or_else_the_uri_authority() { let ok = (StatusCode::OK, "ok".to_string()); @@ -265,6 +689,81 @@ mod tests { ); } + #[tokio::test] + async fn the_guard_reads_the_token_header_and_counts_two_as_none() { + let policy = policy(true); + let token = policy.token.as_str(); + let status = |req: Request| async { through(&policy, req).await.0 }; + + assert_eq!(status(get_with("/api/x", &[])).await, StatusCode::FORBIDDEN); + assert_eq!( + status(get_with("/api/x", &[("x-fleetify-token", token)])).await, + StatusCode::OK + ); + assert_eq!( + status(get_with("/api/x", &[("X-Fleetify-Token", token)])).await, + StatusCode::OK + ); + assert_eq!( + status(get_with( + "/api/x", + &[(API_TOKEN_HEADER, token), (API_TOKEN_HEADER, token)] + )) + .await, + StatusCode::FORBIDDEN + ); + } + + #[tokio::test] + async fn the_guard_takes_the_query_token_on_a_socket_upgrade_or_the_status_stream() { + let policy = policy(true); + let token = policy.token.as_str(); + let status = |req: Request| async { through(&policy, req).await.0 }; + let upgrade = [("connection", "Upgrade"), ("upgrade", "websocket")]; + let socket = format!("/ws/x?{API_TOKEN_QUERY}={token}"); + + assert_eq!(status(get_with(&socket, &upgrade)).await, StatusCode::OK); + // Connection is a list, and both values are case-insensitive. + assert_eq!( + status(get_with( + &socket, + &[ + ("connection", "keep-alive, upgrade"), + ("upgrade", "WebSocket") + ] + )) + .await, + StatusCode::OK + ); + // Not a WebSocket upgrade. + for headers in [ + &[][..], + &[("upgrade", "websocket")][..], + &[("connection", "upgrade"), ("upgrade", "h2c")][..], + ] { + assert_eq!( + status(get_with(&socket, headers)).await, + StatusCode::FORBIDDEN + ); + } + // The value is percent-decoded, as any query value is. + let encoded = format!( + "/ws/x?other=1&{API_TOKEN_QUERY}=%{:02X}{}", + token.as_bytes()[0], + &token[1..] + ); + assert_eq!(status(get_with(&encoded, &upgrade)).await, StatusCode::OK); + // Twice counts as none. + let twice = format!("/ws/x?{API_TOKEN_QUERY}={token}&{API_TOKEN_QUERY}={token}"); + assert_eq!( + status(get_with(&twice, &upgrade)).await, + StatusCode::FORBIDDEN + ); + // The status stream takes it without an upgrade. + let stream = format!("/events/status?{API_TOKEN_QUERY}={token}"); + assert_eq!(status(get_with(&stream, &[])).await, StatusCode::OK); + } + #[tokio::test] async fn a_refusal_is_logged_with_its_path_and_never_its_query() { let logs = LogCapture::start(); @@ -284,4 +783,24 @@ mod tests { assert!(text.contains(r#"path="/api/x""#), "{text}"); assert!(!text.contains("SECRET"), "the query string was logged"); } + + #[tokio::test] + async fn a_token_refusal_is_plain_text_and_its_log_line_has_neither_token() { + let logs = LogCapture::start(); + let req = get_with( + "/api/x?api_token=query-SECRET", + &[(API_TOKEN_HEADER, "header-SECRET")], + ); + let (status, body) = through(&policy(true), req).await; + let text = logs.text(); + + assert_eq!( + (status, body.as_str()), + (StatusCode::FORBIDDEN, "forbidden") + ); + assert!(text.contains(r#"reason="token""#), "{text}"); + assert!(text.contains("method=GET"), "{text}"); + assert!(text.contains(r#"path="/api/x""#), "{text}"); + assert!(!text.contains("SECRET"), "a token was logged"); + } } diff --git a/crates/fleetify-backend/src/http.rs b/crates/fleetify-backend/src/http.rs index b8e248e..52774b8 100644 --- a/crates/fleetify-backend/src/http.rs +++ b/crates/fleetify-backend/src/http.rs @@ -46,9 +46,9 @@ pub fn app(state: AppState, static_dir: Option, policy: AccessPolicy) - .merge(crate::studio::router()); // Loopback-gated internal endpoints (no JWT auth — the - // X-Fleet-Internal header is the only authenticator). Kept off - // `/api` so a renderer hitting it without the header just gets - // 404 instead of a misleading 401. + // X-Fleet-Internal header is the only authenticator). Mounted at + // `/api/internal`, which the access guard asks for no API token: the + // shell and the agents' helper processes call them with the secret. let internal_api = internal::router().merge(browser::internal_router()); let routed = Router::new() diff --git a/crates/fleetify-backend/src/lib.rs b/crates/fleetify-backend/src/lib.rs index 89f74fc..14a62ed 100644 --- a/crates/fleetify-backend/src/lib.rs +++ b/crates/fleetify-backend/src/lib.rs @@ -175,10 +175,19 @@ pub(crate) fn should_load_dotenv(release_build: bool) -> bool { !release_build } +/// `FLEETIFY_REQUIRE_API_TOKEN=1`: a debug build asks for the API token even +/// when it runs with `FLEETIFY_NOAUTH=1`. A release build never reads the +/// variable; it always asks ([`access::token_required`]). +fn api_token_forced() -> bool { + cfg!(debug_assertions) && std::env::var("FLEETIFY_REQUIRE_API_TOKEN").as_deref() == Ok("1") +} + /// Bind `addr` and start serving on a background task, with the UI files, /// external routers and API token in `opts`. The access guard /// ([`access::guard`]) answers only requests addressed to the port actually -/// bound. +/// bound, and asks API requests for the token unless this is a debug build +/// running with `FLEETIFY_NOAUTH=1` (and without +/// `FLEETIFY_REQUIRE_API_TOKEN=1`). Both are read once, here. pub async fn serve(addr: SocketAddr, opts: ServeOptions) -> anyhow::Result { let ServeOptions { static_dir, @@ -406,9 +415,20 @@ pub async fn serve(addr: SocketAddr, opts: ServeOptions) -> anyhow::Result` header (the secret is generated at //! backend startup and injected into the MCP's env via //! `ClaudeBridge::build_mcp_config`). JWT auth is skipped — the -//! secret is the only authenticator here, and the endpoint is -//! intentionally not in `/api` so missing config can't accidentally -//! expose it to a CORS-allowed renderer call. +//! secret is the only authenticator here. These routes are mounted +//! under `/api/internal`, which the access guard (`crate::access`) +//! asks for no API token, so each handler's secret check is what +//! admits a request. //! //! Faithful with the Python `dispatch_mcp.py` flow: //! 1. Resolve `agent` (UUID or case-insensitive title) → session_id. diff --git a/crates/fleetify-backend/tests/access.rs b/crates/fleetify-backend/tests/access.rs index 849f24a..660f832 100644 --- a/crates/fleetify-backend/tests/access.rs +++ b/crates/fleetify-backend/tests/access.rs @@ -1,6 +1,12 @@ //! The access guard over the real `serve()` stack: the backend answers only //! requests addressed to its own host (`127.0.0.1:` or -//! `localhost:`), on every path, and sends no CORS headers. +//! `localhost:`), on every path, and sends no CORS headers. API +//! requests also need this run's token: in the `X-Fleetify-Token` header, +//! or, for a WebSocket upgrade or the status stream, in the `api_token` +//! query parameter. +//! +//! These tests never print a token: a URL with the token in its query is +//! left out of every failure message. mod common; @@ -8,11 +14,15 @@ use std::net::SocketAddr; use std::time::Duration; use common::TestServer; -use fleetify_backend::access::ApiToken; +use fleetify_backend::access::{ApiToken, API_TOKEN_HEADER, API_TOKEN_QUERY}; use fleetify_backend::ServeOptions; +use tokio_tungstenite::tungstenite::Error as WsError; +/// An in-memory database, and auth on: `FLEETIFY_NOAUTH=1` would also turn +/// off the token check these tests are about. fn in_memory_db() { std::env::set_var("FLEET_DB_URL", "sqlite::memory:"); + std::env::remove_var("FLEETIFY_NOAUTH"); } async fn start() -> TestServer { @@ -62,10 +72,10 @@ async fn raw_exchange(addr: SocketAddr, request: &str) -> String { } #[tokio::test] -async fn healthz_answers_on_its_own_address() { +async fn healthz_answers_on_its_own_address_without_a_token() { let server = start().await; let resp = server - .client() + .client_without_token() .get(server.url("/healthz")) .send() .await @@ -134,7 +144,8 @@ async fn a_cross_origin_preflight_gets_no_cors_headers() { } /// The guard is the outermost layer, so the static-file fallback is behind -/// it too: the UI is served to its own address and refused to any other. +/// it too: the UI is served to its own address, without a token, and +/// refused to any other. #[tokio::test] async fn the_ui_files_are_behind_the_host_check() { in_memory_db(); @@ -146,7 +157,12 @@ async fn the_ui_files_are_behind_the_host_check() { }) .await; - let served = server.client().get(server.url("/")).send().await.unwrap(); + let served = server + .client_without_token() + .get(server.url("/")) + .send() + .await + .unwrap(); assert_eq!(served.status(), 200); assert!(served.text().await.unwrap().contains("FLEET-UI")); @@ -157,3 +173,141 @@ async fn the_ui_files_are_behind_the_host_check() { let refused = get_with_host(&server, "/index.html", &evil).await; assert_eq!(refused.status(), 403); } + +#[tokio::test] +async fn an_api_request_needs_the_token_header() { + let server = start().await; + let url = server.url("/api/groups"); + + let without = server + .client_without_token() + .get(&url) + .send() + .await + .unwrap(); + assert_eq!(without.status(), 403); + assert_plain_text(&without); + assert_eq!(without.text().await.unwrap(), "forbidden"); + + let with = server.client().get(&url).send().await.unwrap(); + assert_eq!(with.status(), 200); + + let other = ApiToken::generate(); + let wrong = server + .client_without_token() + .get(&url) + .header(API_TOKEN_HEADER, other.as_str()) + .send() + .await + .unwrap(); + assert_eq!(wrong.status(), 403); +} + +#[tokio::test] +async fn the_status_stream_takes_the_token_in_its_query() { + let server = start().await; + let url = format!( + "{}?{API_TOKEN_QUERY}={}", + server.url("/events/status"), + server.token.as_str() + ); + + let resp = server + .client_without_token() + .get(&url) + .send() + .await + .map_err(|e| e.without_url()) + .unwrap(); + assert_eq!(resp.status(), 200); + let content_type = resp + .headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .unwrap_or_default(); + assert!( + content_type.starts_with("text/event-stream"), + "content-type: {content_type:?}" + ); + drop(resp); + + let without = server + .client_without_token() + .get(server.url("/events/status")) + .send() + .await + .unwrap(); + assert_eq!(without.status(), 403); +} + +/// What a failed handshake says, without its URL. +fn handshake_failure(e: &WsError) -> String { + match e { + WsError::Http(resp) => format!("HTTP {}", resp.status()), + WsError::Io(io) => format!("I/O error: {io}"), + _ => "a WebSocket protocol error".to_string(), + } +} + +#[tokio::test] +async fn a_socket_upgrade_takes_the_token_in_its_query() { + let server = start().await; + let socket_url = format!("ws://{}/ws/browser-url", server.addr()); + + let with_token = format!("{socket_url}?{API_TOKEN_QUERY}={}", server.token.as_str()); + let (socket, response) = tokio_tungstenite::connect_async(with_token) + .await + .unwrap_or_else(|e| { + panic!( + "the upgrade with the token failed: {}", + handshake_failure(&e) + ) + }); + assert_eq!(response.status(), 101); + drop(socket); + + match tokio_tungstenite::connect_async(socket_url).await { + Err(WsError::Http(resp)) => assert_eq!(resp.status(), 403), + Err(e) => panic!( + "the upgrade without a token failed another way: {}", + handshake_failure(&e) + ), + Ok(_) => panic!("the upgrade without a token was accepted"), + } +} + +/// The system browser's OAuth redirect can't carry the token; the handler +/// answers it (here: no `code` and `state`). +#[tokio::test] +async fn the_mcp_oauth_callback_needs_no_token() { + let server = start().await; + let resp = server + .client_without_token() + .get(server.url("/api/mcp/auth/callback")) + .send() + .await + .unwrap(); + assert_eq!(resp.status(), 200); + let body: serde_json::Value = resp.json().await.unwrap(); + assert_eq!(body["ok"], false); +} + +/// The internal routes need no token; their handlers check the internal +/// secret, so without it the answer is the handler's 403, not the guard's. +#[tokio::test] +async fn an_internal_route_needs_no_token_and_its_handler_checks_the_secret() { + let server = start().await; + let resp = server + .client_without_token() + .post(server.url("/api/internal/dispatch")) + .json(&serde_json::json!({ + "caller_session_id": "caller", + "agent": "worker", + "task": "review the diff", + })) + .send() + .await + .unwrap(); + assert_eq!(resp.status(), 403); + assert_eq!(resp.text().await.unwrap(), "internal-secret mismatch"); +} diff --git a/crates/fleetify-backend/tests/common/mod.rs b/crates/fleetify-backend/tests/common/mod.rs index a9e93ef..e32b62d 100644 --- a/crates/fleetify-backend/tests/common/mod.rs +++ b/crates/fleetify-backend/tests/common/mod.rs @@ -1,5 +1,5 @@ //! Shared by the integration tests: the real backend, started with -//! `serve()` on an ephemeral loopback port, and an HTTP client for it. A +//! `serve()` on an ephemeral loopback port, and HTTP clients for it. A //! test file pulls it in with `mod common;`. //! //! It sets no environment variables: each test still sets the ones it needs @@ -12,7 +12,7 @@ use std::net::SocketAddr; -use fleetify_backend::access::ApiToken; +use fleetify_backend::access::{ApiToken, API_TOKEN_HEADER}; use fleetify_backend::{ServeOptions, ServerHandle}; /// A running backend. Dropping it shuts the server down, so keep it alive @@ -52,13 +52,28 @@ impl TestServer { format!("http://{}{path}", self.addr()) } - /// A client for this server. Every request it sends carries - /// `default_headers`, unless the request sets that header itself. + /// A client for this server. Every request it sends carries the + /// server's token in `X-Fleetify-Token`, unless the request sets that + /// header itself. The header is marked sensitive, so the client's debug + /// output never shows it. pub fn client(&self) -> reqwest::Client { - let default_headers = reqwest::header::HeaderMap::new(); + let mut token = reqwest::header::HeaderValue::from_str(self.token.as_str()) + .expect("a token is a valid header value"); + token.set_sensitive(true); + let mut default_headers = reqwest::header::HeaderMap::new(); + default_headers.insert(API_TOKEN_HEADER, token); reqwest::Client::builder() .default_headers(default_headers) .build() .expect("build the test client") } + + /// A client that sends no token, for the checks that a request without + /// one (or with a wrong one, set per request) is refused. reqwest can't + /// drop a default header from one request, so this is a second client. + pub fn client_without_token(&self) -> reqwest::Client { + reqwest::Client::builder() + .build() + .expect("build the test client") + } } diff --git a/crates/fleetify-backend/tests/phase4_apis.rs b/crates/fleetify-backend/tests/phase4_apis.rs index fc65962..f7ad297 100644 --- a/crates/fleetify-backend/tests/phase4_apis.rs +++ b/crates/fleetify-backend/tests/phase4_apis.rs @@ -5,12 +5,12 @@ //! Same RSA + mock-JWKS pattern as sessions_api.rs so the same set of //! integration deps are shared. -use std::net::SocketAddr; +mod common; + use std::time::{SystemTime, UNIX_EPOCH}; use base64::Engine; -use fleetify_backend::access::ApiToken; -use fleetify_backend::ServeOptions; +use common::TestServer; use jsonwebtoken::{encode, EncodingKey, Header}; use rsa::pkcs8::EncodePrivateKey; use rsa::traits::PublicKeyParts; @@ -72,14 +72,11 @@ async fn phase4_apis_smoke() { let token = encode(&header, &claims, &key).unwrap(); let auth = format!("Bearer {token}"); - // 4. Start backend on an ephemeral port. - let addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); - let handle = fleetify_backend::serve(addr, ServeOptions::api_only(ApiToken::generate())) - .await - .unwrap(); - let base = format!("http://{}", handle.local_addr()); + // 4. Start backend on an ephemeral port. Its client sends the API token. + let server = TestServer::start().await; + let base = server.url(""); - let client = reqwest::Client::new(); + let client = server.client(); // ── /api/marketplace/sources auto-seeds Fleetify Official on first hit ── let r = client diff --git a/crates/fleetify-backend/tests/sessions_api.rs b/crates/fleetify-backend/tests/sessions_api.rs index 17b6b33..751cf8d 100644 --- a/crates/fleetify-backend/tests/sessions_api.rs +++ b/crates/fleetify-backend/tests/sessions_api.rs @@ -2,12 +2,12 @@ //! Mocks the IdP JWKS, mints a JWT, then exercises the faithful /api flow: //! /healthz shape, POST/GET /api/sessions round-trip, 401 without bearer. -use std::net::SocketAddr; +mod common; + use std::time::{SystemTime, UNIX_EPOCH}; use base64::Engine; -use fleetify_backend::access::ApiToken; -use fleetify_backend::ServeOptions; +use common::TestServer; use jsonwebtoken::{encode, EncodingKey, Header}; use rsa::pkcs8::EncodePrivateKey; use rsa::traits::PublicKeyParts; @@ -55,11 +55,8 @@ async fn sessions_api_round_trip_with_auth() { std::env::set_var("FLEETIFY_AUDIENCE", "http://127.0.0.1:8765"); // 4. Boot the real backend. - let addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); - let handle = fleetify_backend::serve(addr, ServeOptions::api_only(ApiToken::generate())) - .await - .expect("serve"); - let base = format!("http://{}", handle.local_addr()); + let server = TestServer::start().await; + let base = server.url(""); // 5. Mint a valid JWT (iss = auth_base, aud = expected). let mut header = Header::new(jsonwebtoken::Algorithm::RS256); @@ -76,7 +73,8 @@ async fn sessions_api_round_trip_with_auth() { ) .unwrap(); - let client = reqwest::Client::new(); + // Every request carries the API token; the bearer is per request. + let client = server.client(); // /healthz shape (parity {"status":"ok","version":"0.1.0"}). let hz: serde_json::Value = client @@ -128,5 +126,5 @@ async fn sessions_api_round_trip_with_auth() { .unwrap(); assert!(list.as_array().unwrap().iter().any(|x| x["id"] == s["id"])); - handle.shutdown(); + server.handle.shutdown(); } diff --git a/crates/fleetify-backend/tests/ws_protocol.rs b/crates/fleetify-backend/tests/ws_protocol.rs index 6a75e1c..088c1d8 100644 --- a/crates/fleetify-backend/tests/ws_protocol.rs +++ b/crates/fleetify-backend/tests/ws_protocol.rs @@ -1,5 +1,5 @@ //! Phase 1d /ws/sessions protocol smoke (no `claude` CLI required): -//! - auth via ?token=, ping→pong +//! - auth via ?token= (plus the API token in ?api_token=), ping→pong //! - subscribe owned session → init //! - subscribe foreign id → error //! @@ -7,12 +7,13 @@ //! e2e in Tauri dev. The fidelity-critical stream-json parser is unit- //! tested in `bridges::claude::tests`. -use std::net::SocketAddr; +mod common; + use std::time::{Duration, SystemTime, UNIX_EPOCH}; use base64::Engine; -use fleetify_backend::access::ApiToken; -use fleetify_backend::ServeOptions; +use common::TestServer; +use fleetify_backend::access::API_TOKEN_QUERY; use futures_util::{SinkExt, StreamExt}; use jsonwebtoken::{encode, EncodingKey, Header}; use rsa::pkcs8::EncodePrivateKey; @@ -55,12 +56,9 @@ async fn ws_sessions_subscribe_and_ping() { std::env::set_var("FLEETIFY_ISSUER", &origin); std::env::set_var("FLEETIFY_AUDIENCE", "http://127.0.0.1:8765"); - let addr: SocketAddr = "127.0.0.1:0".parse().unwrap(); - let h = fleetify_backend::serve(addr, ServeOptions::api_only(ApiToken::generate())) - .await - .expect("serve"); - let base = format!("http://{}", h.local_addr()); - let ws_base = format!("ws://{}", h.local_addr()); + let server = TestServer::start().await; + let base = server.url(""); + let ws_base = format!("ws://{}", server.addr()); let mut header = Header::new(jsonwebtoken::Algorithm::RS256); header.kid = Some("test".into()); @@ -76,8 +74,9 @@ async fn ws_sessions_subscribe_and_ping() { ) .unwrap(); - // Create a real session via REST (needed for owned-subscribe). - let client = reqwest::Client::new(); + // Create a real session via REST (needed for owned-subscribe). The + // client sends the API token. + let client = server.client(); let s: Value = client .post(format!("{base}/api/sessions")) .bearer_auth(&token) @@ -90,11 +89,13 @@ async fn ws_sessions_subscribe_and_ping() { .unwrap(); let sid = s["id"].as_str().unwrap().to_string(); - // Connect WS with the bearer in the query. - let (mut ws, _) = - tokio_tungstenite::connect_async(format!("{ws_base}/ws/sessions?token={token}")) - .await - .expect("ws connect"); + // Connect WS with the bearer and the API token in the query. + let (mut ws, _) = tokio_tungstenite::connect_async(format!( + "{ws_base}/ws/sessions?token={token}&{API_TOKEN_QUERY}={}", + server.token.as_str() + )) + .await + .expect("ws connect"); // ping → pong ws.send(Frame::Text(json!({"type":"ping"}).to_string())) @@ -126,7 +127,7 @@ async fn ws_sessions_subscribe_and_ping() { assert_eq!(err["session_id"], "00000000-0000-0000-0000-000000000000"); let _ = ws.close(None).await; - h.shutdown(); + server.handle.shutdown(); } async fn recv_json(ws: &mut S) -> Value diff --git a/docs/RUNNING.md b/docs/RUNNING.md index b4cb396..a1b44f0 100644 --- a/docs/RUNNING.md +++ b/docs/RUNNING.md @@ -98,6 +98,7 @@ shipped binary is ~20% smaller than a default release build. | `FLEETIFY_RESOURCE` | `https://fleetify.dev/api` | RFC 8707 resource indicator | | `FLEETIFY_DASHBOARD_URL` | `https://app.fleetify.dev` | "Open dashboard" link target | | `FLEETIFY_NOAUTH` | (unset) | `=1` ⇒ skip OAuth, sign in as a stub "John Doe", disable telemetry. Dev only. | +| `FLEETIFY_REQUIRE_API_TOKEN` | (unset) | `=1` ⇒ the backend asks for the per-run API token even under `FLEETIFY_NOAUTH=1`. Dev only; release builds always ask for it. | | `FLEET_DB_URL` | `sqlite://~/.fleetify/fleet.db?mode=rwc` | Override the local DB; tests set `sqlite::memory:` | | `GEMINI_API_KEY` | (none) | Bypass interactive Gemini OAuth | | `GOOGLE_*` | (none) | Vertex-AI auth (3 vars: API_KEY + PROJECT + LOCATION) | @@ -114,6 +115,10 @@ in Settings but is inert. Use this when the IdP is down or to iterate on UI without a network round-trip — release builds ignore the flag (prod issuer/resource URLs are pinned at compile time). +The backend also stops asking API requests for the per-run token that the +shell hands the renderer, so the UI works from a plain browser tab. Add +`FLEETIFY_REQUIRE_API_TOKEN=1` to keep that check on in a no-auth run. + ### Where things live | Path | Contents | From a43ea807a3096faf8c1e7c01125329d5a4e0c422 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:49:58 +0300 Subject: [PATCH 09/26] fix(workspace): send file actions the bodies the backend expects MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The file tree's create, delete and rename now send what the workspace file API reads. Create sends { path, is_dir }, so "New folder" makes a folder instead of an empty file. Delete sends its path as a JSON body. Rename sends { from, to }, where to is the new name in the same folder, joined with the separator the path already uses; a name that is empty, "." or "..", or contains a separator is refused without a request. All three take success from the reply's ok field, since the API also answers 200 when an action fails. Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- .../workspace/__tests__/file-actions.test.ts | 115 ++++++++++++++++++ src/components/workspace/workspace-panel.tsx | 32 ++++- 2 files changed, 141 insertions(+), 6 deletions(-) create mode 100644 src/components/workspace/__tests__/file-actions.test.ts diff --git a/src/components/workspace/__tests__/file-actions.test.ts b/src/components/workspace/__tests__/file-actions.test.ts new file mode 100644 index 0000000..e37d351 --- /dev/null +++ b/src/components/workspace/__tests__/file-actions.test.ts @@ -0,0 +1,115 @@ +/** + * The file tree's actions against the backend's file API + * (crates/fleetify-backend/src/routers/workspace.rs): create sends + * `{ path, is_dir }`, delete sends `DELETE` with `{ path }` as its JSON body, + * rename sends `{ from, to }`. Each answers `{ ok, error? }`, and the actions + * report success from that `ok`, not from the HTTP status. + */ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { apiCreate, apiDelete, apiRename } from "@/components/workspace/workspace-panel"; + +/** A stubbed fetch that answers every request with `body` as JSON. */ +function answering(body: unknown, status = 200) { + return vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) => + new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } })); +} + +/** What the `n`-th request sent. */ +function sent(fetchMock: ReturnType, n = 0) { + const [input, init] = fetchMock.mock.calls[n] ?? []; + return { + url: String(input), + method: init?.method, + contentType: new Headers(init?.headers).get("Content-Type"), + body: JSON.parse(String(init?.body)) as unknown, + }; +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe("workspace file actions", () => { + it("create sends the path and whether it is a folder", async () => { + const fetchMock = answering({ ok: true }); + vi.stubGlobal("fetch", fetchMock); + + await expect(apiCreate("/repo/src", "folder")).resolves.toBe(true); + await expect(apiCreate("/repo/a.ts", "file")).resolves.toBe(true); + + expect(sent(fetchMock, 0)).toEqual({ + url: "/api/fs/create", + method: "POST", + contentType: "application/json", + body: { path: "/repo/src", is_dir: true }, + }); + expect(sent(fetchMock, 1).body).toEqual({ path: "/repo/a.ts", is_dir: false }); + }); + + it("delete sends DELETE with the path as its JSON body", async () => { + const fetchMock = answering({ ok: true }); + vi.stubGlobal("fetch", fetchMock); + + await expect(apiDelete("/repo/a.ts")).resolves.toBe(true); + + expect(sent(fetchMock)).toEqual({ + url: "/api/fs/delete", + method: "DELETE", + contentType: "application/json", + body: { path: "/repo/a.ts" }, + }); + }); + + it("rename sends from and to, the new name in the same folder", async () => { + const fetchMock = answering({ ok: true }); + vi.stubGlobal("fetch", fetchMock); + + await expect(apiRename("/repo/src/old.ts", "new.ts")).resolves.toEqual({ + ok: true, + path: "/repo/src/new.ts", + }); + + expect(sent(fetchMock)).toEqual({ + url: "/api/fs/rename", + method: "POST", + contentType: "application/json", + body: { from: "/repo/src/old.ts", to: "/repo/src/new.ts" }, + }); + }); + + it("rename keeps a Windows path's separator", async () => { + const fetchMock = answering({ ok: true }); + vi.stubGlobal("fetch", fetchMock); + + await expect(apiRename("C:\\x\\old.txt", "new.txt")).resolves.toEqual({ + ok: true, + path: "C:\\x\\new.txt", + }); + expect(sent(fetchMock).body).toEqual({ from: "C:\\x\\old.txt", to: "C:\\x\\new.txt" }); + }); + + it("rename refuses a name with a separator, or . or .., without a request", async () => { + const fetchMock = answering({ ok: true }); + vi.stubGlobal("fetch", fetchMock); + + for (const name of ["a/b", "a\\b", ".", "..", ""]) { + await expect(apiRename("/repo/old.ts", name), JSON.stringify(name)).resolves.toEqual({ ok: false }); + } + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("each reports success from the reply's ok, not from the HTTP status", async () => { + vi.stubGlobal("fetch", answering({ ok: false, error: "permission denied" })); + + await expect(apiCreate("/repo/x", "file")).resolves.toBe(false); + await expect(apiDelete("/repo/x")).resolves.toBe(false); + await expect(apiRename("/repo/x", "y")).resolves.toMatchObject({ ok: false }); + + // A reply that isn't the JSON envelope (here the access guard's 403). + vi.stubGlobal("fetch", vi.fn(async () => new Response("forbidden", { status: 403 }))); + + await expect(apiCreate("/repo/x", "file")).resolves.toBe(false); + await expect(apiDelete("/repo/x")).resolves.toBe(false); + await expect(apiRename("/repo/x", "y")).resolves.toMatchObject({ ok: false }); + }); +}); diff --git a/src/components/workspace/workspace-panel.tsx b/src/components/workspace/workspace-panel.tsx index 61ee50a..131263b 100644 --- a/src/components/workspace/workspace-panel.tsx +++ b/src/components/workspace/workspace-panel.tsx @@ -114,14 +114,34 @@ async function apiGitDiff(p: string, file?: string, scope: DiffScope = "auto"): return r.ok ? r.json() : { error: "Failed" }; } catch { return { error: "Failed" }; } } -async function apiCreate(path: string, type: "file" | "folder"): Promise { - try { const r = await backendFetch("/api/fs/create", { method:"POST", headers:{"Content-Type":"application/json"}, body: JSON.stringify({ path, type }) }); return r.ok; } catch { return false; } +/* The file actions send the bodies routers/workspace.rs reads (CreateBody, + DeleteBody, RenameBody) and get `{ ok, error? }` back. Success is that + `ok`: a failed action still answers 200. */ +async function fileAction(url: string, method: "POST" | "DELETE", body: unknown): Promise { + try { + const r = await backendFetch(url, { + method, + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), + }); + const reply = (await r.json()) as { ok?: unknown } | null; + return reply?.ok === true; + } catch { return false; } +} +export async function apiCreate(path: string, type: "file" | "folder"): Promise { + return fileAction("/api/fs/create", "POST", { path, is_dir: type === "folder" }); } -async function apiDelete(path: string): Promise { - try { const r = await backendFetch(`/api/fs/delete?path=${encodeURIComponent(path)}`, { method:"DELETE" }); return r.ok; } catch { return false; } +export async function apiDelete(path: string): Promise { + return fileAction("/api/fs/delete", "DELETE", { path }); } -async function apiRename(path: string, name: string): Promise<{ ok: boolean; path?: string }> { - try { const r = await backendFetch("/api/fs/rename", { method:"POST", headers:{"Content-Type":"application/json"}, body: JSON.stringify({ path, name }) }); return r.ok ? r.json() : { ok: false }; } catch { return { ok: false }; } +/* Rename within the same folder: `to` is the parent of `path` plus `name`, + joined with the separator `path` itself uses (`/`, or `\` on Windows). A + name that is empty, `.`, `..` or has a separator is refused unsent. */ +export async function apiRename(path: string, name: string): Promise<{ ok: boolean; path?: string }> { + if (name === "" || name === "." || name === ".." || /[\\/]/.test(name)) return { ok: false }; + const cut = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")); + const to = cut === -1 ? name : path.slice(0, cut + 1) + name; + return { ok: await fileAction("/api/fs/rename", "POST", { from: path, to }), path: to }; } /* ─── Context Menu ─── */ From e687bd3f7f5e571ead9e64d78f73533c0691b0c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:18:16 +0300 Subject: [PATCH 10/26] fix(shell): remove the unused local access-token server MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- README.md | 6 +-- docs/ARCHITECTURE.md | 4 +- src-tauri/src/lib.rs | 13 ++---- src-tauri/src/shell/auth.rs | 2 +- src-tauri/src/shell/bearer.rs | 79 ----------------------------------- src-tauri/src/shell/mod.rs | 56 +++++++++++++++++++++++-- 6 files changed, 62 insertions(+), 98 deletions(-) delete mode 100644 src-tauri/src/shell/bearer.rs diff --git a/README.md b/README.md index e18bf34..2e816e5 100644 --- a/README.md +++ b/README.md @@ -64,9 +64,9 @@ cargo tauri build `fleetify-backend` is library-only — no `main.rs`. The Tauri shell calls `fleetify_backend::serve(addr, static_dir).await` from its `setup` hook; the server runs as a tokio task in the same process. Sign-in lives in -the Tauri shell (`shell::auth`); the bearer is exposed to the backend -via `127.0.0.1:8770` (loopback bearer-bridge) so the React UI can use -the cookie-less OIDC flow without leaking the token across IPC. The 3 +the Tauri shell (`shell::auth`), which holds the access token. The React +UI asks for it over IPC (`auth_get_access_token`); the telemetry client +gets it in-process from `shell::auth`. The 3 MCP-server binaries connect upward to `127.0.0.1:8765/api/sessions/...` when the user's session invokes their tools. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 99d6a28..6f14e48 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -15,8 +15,8 @@ plus cloud HTTP model providers (OpenAI, OpenRouter, …). ``` ┌───────────────────────────── Tauri v2 process ─────────────────────────────┐ │ src-tauri (fleetify-app) │ -│ ├─ shell::auth OIDC sign-in; bearer exposed on 127.0.0.1:8770 │ -│ │ (loopback bearer-bridge, no token across IPC) │ +│ ├─ shell::auth OIDC sign-in; holds the access token │ +│ │ (the renderer asks for it over IPC) │ │ └─ setup() ─ calls ──▶ fleetify_backend::serve(127.0.0.1:8765, dist) │ │ │ (library, no main.rs — runs as a tokio task)│ │ ├─ React UI (built dist/) │ diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 551b3cd..73373d7 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,6 +1,6 @@ //! Tauri v2 shell. `shell/` reimplements the Electron main process -//! (Phase 1b: auth + bearer bridge + auth IPC). `setup` starts the embedded -//! backend, the bearer bridge, and the main window. +//! (Phase 1b: auth + auth IPC). `setup` starts the embedded backend and the +//! main window. mod shell; @@ -655,14 +655,9 @@ pub fn run() { boot_start, )); - // Loopback bearer bridge :8770 (telemetry token source / parity). - // FLEETIFY_NOAUTH=1 has no consumer to feed and no token to - // emit, so skip the listener entirely. + // FLEETIFY_NOAUTH=1 has only a placeholder token, nothing the + // cloud would accept, so the telemetry client doesn't start. if !shell::auth::is_no_auth() { - tauri::async_runtime::spawn(async { - shell::bearer::run().await; - }); - // Telemetry WS client → fleetify.dev. Bearer pulled from // shell::auth.get_access_token() lazily per attempt so a // mid-flow refresh is picked up at the next reconnect. diff --git a/src-tauri/src/shell/auth.rs b/src-tauri/src/shell/auth.rs index 8c1096f..f13398e 100644 --- a/src-tauri/src/shell/auth.rs +++ b/src-tauri/src/shell/auth.rs @@ -383,7 +383,7 @@ pub async fn sign_in() -> Result { Ok(tokens) } -pub async fn refresh_if_needed(force: bool) -> Result { +async fn refresh_if_needed(force: bool) -> Result { if is_no_auth() { return Ok(noauth_tokens()); } diff --git a/src-tauri/src/shell/bearer.rs b/src-tauri/src/shell/bearer.rs deleted file mode 100644 index da5d940..0000000 --- a/src-tauri/src/shell/bearer.rs +++ /dev/null @@ -1,79 +0,0 @@ -//! Loopback bearer bridge — faithful port of `electron/bearer-bridge.cjs`. -//! `GET http://127.0.0.1:8770/auth/access-token`: -//! 200 {token,expires_at} | 401 {error:"not-signed-in"} | -//! 503 {error:"refresh-failed",detail}. Peer hard-pinned to loopback. - -use tokio::io::{AsyncReadExt, AsyncWriteExt}; -use tokio::net::TcpListener; - -pub async fn run() { - let listener = match TcpListener::bind(("127.0.0.1", 8770u16)).await { - Ok(l) => l, - Err(e) => { - tracing::error!("bearer-bridge bind failed: {e}"); - return; - } - }; - tracing::info!("bearer-bridge listening on http://127.0.0.1:8770/auth/access-token"); - loop { - let (mut sock, peer) = match listener.accept().await { - Ok(x) => x, - Err(_) => continue, - }; - tokio::spawn(async move { - let ok_peer = peer.ip().is_loopback(); - let mut buf = [0u8; 2048]; - let n = match sock.read(&mut buf).await { - Ok(n) => n, - Err(_) => return, - }; - let head = String::from_utf8_lossy(&buf[..n]); - let first = head.lines().next().unwrap_or(""); - let mut it = first.split_whitespace(); - let method = it.next().unwrap_or(""); - let path = it.next().unwrap_or(""); - - let (status, body): (u16, String) = if !ok_peer { - (403, String::new()) - } else if method != "GET" || path != "/auth/access-token" { - (404, String::new()) - } else { - match super::auth::refresh_if_needed(false).await { - Ok(t) => ( - 200, - serde_json::json!({"token": t.access_token, "expires_at": t.expires_at}) - .to_string(), - ), - Err(e) => { - let m = e.to_string().to_lowercase(); - if m.contains("no refresh token") || m.contains("invalid_grant") { - ( - 401, - serde_json::json!({"error":"not-signed-in"}).to_string(), - ) - } else { - ( - 503, - serde_json::json!({"error":"refresh-failed","detail": e.to_string()}) - .to_string(), - ) - } - } - } - }; - let reason = match status { - 200 => "OK", - 401 => "Unauthorized", - 403 => "Forbidden", - 404 => "Not Found", - _ => "Service Unavailable", - }; - let resp = format!( - "HTTP/1.1 {status} {reason}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", - body.len(), - body - ); - let _ = sock.write_all(resp.as_bytes()).await; - }); - } -} diff --git a/src-tauri/src/shell/mod.rs b/src-tauri/src/shell/mod.rs index 0fccc55..8598764 100644 --- a/src-tauri/src/shell/mod.rs +++ b/src-tauri/src/shell/mod.rs @@ -1,11 +1,9 @@ -//! Electron main-process equivalents. Phase 1b lands auth, bearer bridge, -//! and auth IPC; the remaining ~51 IPC commands (fs/git/pty/github/…) follow -//! in Phase 1c+. +//! Electron main-process equivalents. Phase 1b lands auth and auth IPC; the +//! remaining ~51 IPC commands (fs/git/pty/github/…) follow in Phase 1c+. pub mod ai_git; pub mod auth; pub mod backend_ready; -pub mod bearer; pub mod config; pub mod feedback; pub mod git; @@ -25,3 +23,53 @@ pub mod routing_setup; pub mod startup_window; pub mod ui_files; pub mod voice; + +#[cfg(test)] +mod tests { + use std::path::{Path, PathBuf}; + + /// Every file under `dir`, however deep. + fn files_under(dir: &Path) -> Vec { + let mut files = Vec::new(); + let mut pending = vec![dir.to_path_buf()]; + while let Some(dir) = pending.pop() { + for entry in std::fs::read_dir(&dir).expect("read a source directory") { + let path = entry.expect("read a directory entry").path(); + if path.is_dir() { + pending.push(path); + } else { + files.push(path); + } + } + } + files + } + + // The renderer gets the access token over IPC and the telemetry client + // gets it in-process, so the app serves it on no port of its own. The + // needles are put together at run time: the walk reads this file too, + // and must not find them in it. + #[test] + fn no_local_token_server() { + let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let needles = [["87", "70"].concat(), ["bearer", "::"].concat()]; + let files = files_under(&src); + assert!( + files.iter().any(|f| f.ends_with(file!())), + "the walk of {} never reached {}", + src.display(), + file!() + ); + let mut hits = Vec::new(); + for file in &files { + let bytes = std::fs::read(file).expect("read a source file"); + let text = String::from_utf8_lossy(&bytes); + for needle in &needles { + if text.contains(needle.as_str()) { + hits.push(format!("{} contains {needle:?}", file.display())); + } + } + } + assert!(hits.is_empty(), "{hits:#?}"); + } +} From f47d21ef90127a0db1d37cca9f52389eb8e48c72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:40:12 +0300 Subject: [PATCH 11/26] fix(shell): keep loopback traffic off environment proxies on Linux MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- crates/fleetify-core/src/loopback.rs | 84 ++++++++++++++++++++++++++++ src-tauri/src/lib.rs | 14 +++++ 2 files changed, 98 insertions(+) diff --git a/crates/fleetify-core/src/loopback.rs b/crates/fleetify-core/src/loopback.rs index c58532c..234f6a2 100644 --- a/crates/fleetify-core/src/loopback.rs +++ b/crates/fleetify-core/src/loopback.rs @@ -12,6 +12,12 @@ //! MCP sidecars, starts from [`http_client_builder`]. Clients that reach the //! internet (providers, the issuer, GitHub) don't: they keep honouring the //! user's proxy. +//! +//! WebKitGTK, the webview on Linux, sends its page loads, the app's own +//! included, through the proxy in `http_proxy` or `HTTP_PROXY` too, unless +//! the host is in the no-proxy list. So on Linux the shell adds the loopback +//! hosts to `NO_PROXY` and `no_proxy` with [`no_proxy_with_loopback`] before +//! the first webview starts. The processes the app starts inherit the list. /// A reqwest client builder for calls to a service the app runs on this /// machine. It never uses a proxy, whatever the environment says. @@ -19,6 +25,30 @@ pub fn http_client_builder() -> reqwest::ClientBuilder { reqwest::Client::builder().no_proxy() } +/// The hosts the app's own services are reached at, as no-proxy entries. +pub const LOOPBACK_NO_PROXY: [&str; 3] = ["localhost", "127.0.0.1", "::1"]; + +/// A no-proxy list that keeps the user's entries and adds +/// [`LOOPBACK_NO_PROXY`]. +/// +/// It holds the entries of `upper` (`NO_PROXY`), then those of `lower` +/// (`no_proxy`), then the loopback hosts, joined with `,`. Entries are +/// trimmed, empty ones are dropped, and a repeat (ignoring ASCII case) is +/// dropped too, so the first spelling stays. +pub fn no_proxy_with_loopback(upper: Option<&str>, lower: Option<&str>) -> String { + let listed = upper + .into_iter() + .chain(lower) + .flat_map(|list| list.split(',')); + let mut entries: Vec<&str> = Vec::new(); + for entry in listed.chain(LOOPBACK_NO_PROXY).map(str::trim) { + if !entry.is_empty() && !entries.iter().any(|kept| kept.eq_ignore_ascii_case(entry)) { + entries.push(entry); + } + } + entries.join(",") +} + #[cfg(test)] mod tests { use super::*; @@ -125,4 +155,58 @@ mod tests { assert_eq!(response.text().await.unwrap(), "loopback"); }); } + + #[test] + fn no_proxy_without_a_list_is_the_loopback_hosts() { + assert_eq!( + no_proxy_with_loopback(None, None), + "localhost,127.0.0.1,::1" + ); + } + + #[test] + fn no_proxy_keeps_the_users_entries_first() { + assert_eq!( + no_proxy_with_loopback(Some("corp.example"), None), + "corp.example,localhost,127.0.0.1,::1" + ); + } + + #[test] + fn no_proxy_takes_the_upper_case_list_then_the_lower_case_one() { + assert_eq!( + no_proxy_with_loopback(Some("a"), Some("b")), + "a,b,localhost,127.0.0.1,::1" + ); + } + + #[test] + fn no_proxy_trims_entries_and_drops_empty_and_repeated_ones() { + assert_eq!( + no_proxy_with_loopback(Some(" localhost , 127.0.0.1,,x "), None), + "localhost,127.0.0.1,x,::1" + ); + } + + #[test] + fn no_proxy_keeps_a_wildcard() { + assert_eq!( + no_proxy_with_loopback(Some("*"), None), + "*,localhost,127.0.0.1,::1" + ); + } + + #[test] + fn no_proxy_drops_a_repeat_in_another_case_keeping_the_first_spelling() { + assert_eq!( + no_proxy_with_loopback(Some("Corp.Example,LOCALHOST"), Some("corp.example,::1")), + "Corp.Example,LOCALHOST,::1,127.0.0.1" + ); + } + + #[test] + fn no_proxy_is_unchanged_when_both_variables_already_hold_it() { + let set = "corp.example,localhost,127.0.0.1,::1"; + assert_eq!(no_proxy_with_loopback(Some(set), Some(set)), set); + } } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 73373d7..b21a534 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -36,6 +36,20 @@ fn vite_port() -> u16 { #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { + // WebKitGTK sends even the app's own page loads through the proxy in + // `http_proxy`/`HTTP_PROXY`, so the loopback hosts join `NO_PROXY` (read + // first by hyper-util) and `no_proxy` (read first by curl). + // Runs first: WebKit's network process copies the environment when the first webview starts. + #[cfg(target_os = "linux")] + { + let no_proxy = fleetify_core::loopback::no_proxy_with_loopback( + std::env::var("NO_PROXY").ok().as_deref(), + std::env::var("no_proxy").ok().as_deref(), + ); + std::env::set_var("NO_PROXY", &no_proxy); + std::env::set_var("no_proxy", &no_proxy); + } + // Tracing init moved into `setup()` so the file appender can use // Tauri's resolved `app_log_dir()` (Windows: %LOCALAPPDATA%, macOS: // ~/Library/Logs, Linux: ~/.local/state). The WorkerGuard returned From f212498232cf9cc30afdd6da3e724855300a7751 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:54:45 +0300 Subject: [PATCH 12/26] fix(shell): keep a match-all no_proxy and lowercase entries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- crates/fleetify-core/src/loopback.rs | 50 +++++++++++++++++++++------- 1 file changed, 38 insertions(+), 12 deletions(-) diff --git a/crates/fleetify-core/src/loopback.rs b/crates/fleetify-core/src/loopback.rs index 234f6a2..d6006fd 100644 --- a/crates/fleetify-core/src/loopback.rs +++ b/crates/fleetify-core/src/loopback.rs @@ -33,16 +33,27 @@ pub const LOOPBACK_NO_PROXY: [&str; 3] = ["localhost", "127.0.0.1", "::1"]; /// /// It holds the entries of `upper` (`NO_PROXY`), then those of `lower` /// (`no_proxy`), then the loopback hosts, joined with `,`. Entries are -/// trimmed, empty ones are dropped, and a repeat (ignoring ASCII case) is -/// dropped too, so the first spelling stays. +/// trimmed and ASCII-lowercased, and empty or repeated ones are dropped. +/// Lowercase is the form that matches: libproxy compares host names +/// case-sensitively, and a parsed URL's host is lowercase. +/// +/// If either list has an entry that is exactly `*`, the result is `*` alone. +/// That already exempts every host, and curl (git too) treats the list as +/// match-all only when the whole value is `*`. pub fn no_proxy_with_loopback(upper: Option<&str>, lower: Option<&str>) -> String { - let listed = upper + let listed: Vec<&str> = upper .into_iter() .chain(lower) - .flat_map(|list| list.split(',')); - let mut entries: Vec<&str> = Vec::new(); - for entry in listed.chain(LOOPBACK_NO_PROXY).map(str::trim) { - if !entry.is_empty() && !entries.iter().any(|kept| kept.eq_ignore_ascii_case(entry)) { + .flat_map(|list| list.split(',')) + .map(str::trim) + .collect(); + if listed.contains(&"*") { + return "*".to_owned(); + } + let mut entries: Vec = Vec::new(); + for entry in listed.into_iter().chain(LOOPBACK_NO_PROXY) { + let entry = entry.to_ascii_lowercase(); + if !entry.is_empty() && !entries.contains(&entry) { entries.push(entry); } } @@ -189,18 +200,33 @@ mod tests { } #[test] - fn no_proxy_keeps_a_wildcard() { + fn no_proxy_with_a_wildcard_is_the_wildcard_alone() { + assert_eq!(no_proxy_with_loopback(Some("*"), None), "*"); + } + + #[test] + fn no_proxy_with_a_wildcard_among_other_entries_is_the_wildcard_alone() { + assert_eq!(no_proxy_with_loopback(Some("a, * ,b"), Some("c")), "*"); + assert_eq!(no_proxy_with_loopback(Some("a"), Some(" * ")), "*"); + } + + #[test] + fn no_proxy_treats_a_wildcard_inside_an_entry_as_an_ordinary_entry() { assert_eq!( - no_proxy_with_loopback(Some("*"), None), - "*,localhost,127.0.0.1,::1" + no_proxy_with_loopback(Some("*.corp.example"), None), + "*.corp.example,localhost,127.0.0.1,::1" ); } #[test] - fn no_proxy_drops_a_repeat_in_another_case_keeping_the_first_spelling() { + fn no_proxy_lowercases_entries_so_a_repeat_in_another_case_is_dropped() { + assert_eq!( + no_proxy_with_loopback(Some("LOCALHOST"), None), + "localhost,127.0.0.1,::1" + ); assert_eq!( no_proxy_with_loopback(Some("Corp.Example,LOCALHOST"), Some("corp.example,::1")), - "Corp.Example,LOCALHOST,::1,127.0.0.1" + "corp.example,localhost,::1,127.0.0.1" ); } From e3927b6e9776263e2ce26e3136bcdf902cb7056d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:12:45 +0300 Subject: [PATCH 13/26] chore(telemetry): default product analytics to PostHog's EU region MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- .env.example | 9 ++--- CLAUDE.md | 8 ++--- .../src/services/telemetry/posthog/mod.rs | 35 ++++++++++++++----- docs/ANALYTICS.md | 6 +++- scripts/dev-tauri-wt.mjs | 2 +- src/lib/__tests__/posthog.test.ts | 2 +- src/lib/posthog.ts | 3 +- 7 files changed, 44 insertions(+), 21 deletions(-) diff --git a/.env.example b/.env.example index 090787d..4dfe2a0 100644 --- a/.env.example +++ b/.env.example @@ -12,12 +12,13 @@ # PostHog product analytics. Both halves should match so backend + frontend # events flow into the same PostHog project. Keys are `phc_*` public keys -# by design; safe to embed in shipped binaries. Default host is US cloud — -# set the *_HOST pair to https://eu.i.posthog.com for EU residency. +# by design; safe to embed in shipped binaries. The default host is +# PostHog's EU cloud; a project in the US cloud sets both *_HOST values +# to https://us.i.posthog.com instead. POSTHOG_API_KEY= VITE_POSTHOG_KEY= -POSTHOG_HOST=https://us.i.posthog.com -VITE_POSTHOG_HOST=https://us.i.posthog.com +POSTHOG_HOST=https://eu.i.posthog.com +VITE_POSTHOG_HOST=https://eu.i.posthog.com # Not Diamond — Fleet-owned routing key for the "Auto" model picker. Read at # runtime by the backend (std::env::var). Fleet's own key, independent of any diff --git a/CLAUDE.md b/CLAUDE.md index 094b5c9..2c1b77a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -256,19 +256,19 @@ sends. - **Code:** backend module at `crates/fleetify-backend/src/services/telemetry/posthog/`; frontend wrapper at `src/lib/posthog.ts`. - **Fan-out:** the existing `services/telemetry/emitters.rs::enqueue_payload` writes to both the Fleetify cloud outbox AND the PostHog outbox (the latter via `posthog::enqueue_if_enabled`, gated on a runtime `AtomicBool`). - **distinct_id:** the persisted `device_id` from `device.json` is reused on both sides. Frontend `posthog.identify(user_id)` runs at sign-in, at each launch while signed in, and at opt-in, and only while product analytics is on; it merges the anonymous person into the authenticated one via `$anon_distinct_id`, with the id only (`before_send` strips `$set` / `$set_once`). -- **Env keys:** `POSTHOG_API_KEY` (Rust, runtime `std::env::var`) and `VITE_POSTHOG_KEY` (Vite, `import.meta.env`). Unset → backend `init` short-circuits and the renderer wrapper no-ops. `POSTHOG_HOST` / `VITE_POSTHOG_HOST` default to `https://us.i.posthog.com`. +- **Env keys:** `POSTHOG_API_KEY` (Rust, runtime `std::env::var`) and `VITE_POSTHOG_KEY` (Vite, `import.meta.env`). Unset → backend `init` short-circuits and the renderer wrapper no-ops. `POSTHOG_HOST` / `VITE_POSTHOG_HOST` default to `https://eu.i.posthog.com`. - **Runtime gate:** `telemetry_set_posthog_enabled` Tauri command persists the flag in `fleet.config.json::telemetry.posthog_enabled` AND flips the backend's `ENABLED` atomic live. Live opt-out stops new sends within ~10 s; the renderer's `optOut()` opts posthog-js out at once and drops every request it would still make, queued events and retries included. ### Local dev -Single source of truth is a `.env` file in the workspace root (gitignored — `.env.example` is the committed template). `dotenvy::dotenv()` runs at the top of `serve_with_routing_setup` so the Rust backend picks up the keys via `std::env::var`; Vite reads the same `.env` natively for the renderer. +Single source of truth is a `.env` file in the workspace root (gitignored — `.env.example` is the committed template). `dotenvy::dotenv()` runs at the top of `serve` so the Rust backend picks up the keys via `std::env::var`; Vite reads the same `.env` natively for the renderer. ``` # .env (gitignored) POSTHOG_API_KEY=phc_yourtestprojectkey VITE_POSTHOG_KEY=phc_yourtestprojectkey -POSTHOG_HOST=https://us.i.posthog.com -VITE_POSTHOG_HOST=https://us.i.posthog.com +POSTHOG_HOST=https://eu.i.posthog.com +VITE_POSTHOG_HOST=https://eu.i.posthog.com ``` Then just run `npm run dev:tauri:wt` — no shell env juggling, no `cargo clean` needed because the keys are read at runtime now (was `option_env!` baked-at-compile, dropped in favour of runtime resolution). Shell-set env vars still win over `.env` so CI / production injection paths are unchanged. diff --git a/crates/fleetify-backend/src/services/telemetry/posthog/mod.rs b/crates/fleetify-backend/src/services/telemetry/posthog/mod.rs index 04aa6f6..07ee5fd 100644 --- a/crates/fleetify-backend/src/services/telemetry/posthog/mod.rs +++ b/crates/fleetify-backend/src/services/telemetry/posthog/mod.rs @@ -48,13 +48,19 @@ pub fn project_key() -> Option { .filter(|s| !s.is_empty()) } -/// PostHog host. Defaults to US cloud; override at runtime with -/// `POSTHOG_HOST=https://eu.i.posthog.com` (or a self-hosted URL). +/// The default PostHog host: PostHog Cloud's EU region. The renderer +/// keeps the same default in `src/lib/posthog.ts`. +pub const DEFAULT_HOST: &str = "https://eu.i.posthog.com"; + +/// PostHog host: `POSTHOG_HOST` from the process environment at call +/// time, or [`DEFAULT_HOST`] when it is unset or empty. A project in +/// PostHog's US region, or a self-hosted instance, sets `POSTHOG_HOST` +/// to its own URL. pub fn host() -> String { std::env::var("POSTHOG_HOST") .ok() .filter(|s| !s.is_empty()) - .unwrap_or_else(|| "https://us.i.posthog.com".to_string()) + .unwrap_or_else(|| DEFAULT_HOST.to_string()) } /// Distinct ID = the persisted device_id from `device_id::get_or_create`. @@ -131,12 +137,23 @@ mod tests { use super::*; #[test] - fn host_defaults_to_us_cloud() { - // When POSTHOG_HOST is unset at build time, default to US. - // (Local tests inherit the build-time value of option_env!, so - // this just sanity-checks the string is well-formed.) - let h = host(); - assert!(h.starts_with("http"), "host should be a URL: {h}"); + fn host_defaults_to_eu() { + // POSTHOG_HOST is process-wide: change it only under the crate's + // env lock, and put back whatever was there before asserting. + let _g = crate::test_support::home_lock() + .lock() + .unwrap_or_else(|p| p.into_inner()); + let prev = std::env::var_os("POSTHOG_HOST"); + std::env::remove_var("POSTHOG_HOST"); + let unset = host(); + std::env::set_var("POSTHOG_HOST", ""); + let empty = host(); + match prev { + Some(v) => std::env::set_var("POSTHOG_HOST", v), + None => std::env::remove_var("POSTHOG_HOST"), + } + assert_eq!(unset, "https://eu.i.posthog.com"); + assert_eq!(empty, "https://eu.i.posthog.com"); } #[test] diff --git a/docs/ANALYTICS.md b/docs/ANALYTICS.md index c73031d..ed73d01 100644 --- a/docs/ANALYTICS.md +++ b/docs/ANALYTICS.md @@ -8,7 +8,11 @@ Privacy**. | Channel | Destination | Default | Settings | |---|---|---|---| | `Dashboard sync` | Fleetify cloud (`fleetify.dev`) | **ON** | Privacy → Dashboard sync | -| `Product analytics` | PostHog Cloud (US) | **OFF** | Privacy → Product analytics | +| `Product analytics` | PostHog Cloud (EU, Frankfurt) | **OFF** | Privacy → Product analytics | + +PostHog derives an approximate location, such as the country and city, +from the IP address each event comes from; Fleetify's PostHog project +then discards the address. Onboarding ends with one step for each. The first tells you what dashboard sync sends and that it is on, with two buttons: **Keep it on** diff --git a/scripts/dev-tauri-wt.mjs b/scripts/dev-tauri-wt.mjs index 46011ab..5121d9e 100644 --- a/scripts/dev-tauri-wt.mjs +++ b/scripts/dev-tauri-wt.mjs @@ -119,7 +119,7 @@ function main() { // calls `dotenvy::dotenv()` at startup, so a workspace-root `.env` // (gitignored; see `.env.example` for the template) feeds straight // in without any wrapper shell-export step. Defaults live in code: - // backend defaults POSTHOG_HOST to `https://us.i.posthog.com`, the + // backend defaults POSTHOG_HOST to `https://eu.i.posthog.com`, the // renderer's `src/lib/posthog.ts` does the same for VITE_POSTHOG_HOST. // // NOTE: do NOT add explicit `POSTHOG_API_KEY: process.env... ?? ''` diff --git a/src/lib/__tests__/posthog.test.ts b/src/lib/__tests__/posthog.test.ts index b94a658..6b8b255 100644 --- a/src/lib/__tests__/posthog.test.ts +++ b/src/lib/__tests__/posthog.test.ts @@ -38,7 +38,7 @@ let analytics: typeof import("@/lib/posthog"); let send: ReturnType; const EXPECTED_OPTIONS = { - api_host: "https://us.i.posthog.com", + api_host: "https://eu.i.posthog.com", autocapture: false, capture_pageview: false, capture_pageleave: false, diff --git a/src/lib/posthog.ts b/src/lib/posthog.ts index 4b6282e..9233136 100644 --- a/src/lib/posthog.ts +++ b/src/lib/posthog.ts @@ -27,8 +27,9 @@ import type { CaptureResult, PostHog, PostHogConfig } from "posthog-js"; const projectKey = () => (import.meta.env.VITE_POSTHOG_KEY as string | undefined) || undefined; +/** `VITE_POSTHOG_HOST`, or PostHog Cloud's EU region (the backend's `posthog::DEFAULT_HOST`). */ const apiHost = () => - (import.meta.env.VITE_POSTHOG_HOST as string | undefined) || "https://us.i.posthog.com"; + (import.meta.env.VITE_POSTHOG_HOST as string | undefined) || "https://eu.i.posthog.com"; /** * Everything posthog-js would send or fetch beyond Fleetify's own events From 1f46ce11e8873d2afaf836eead6c339f41ff9473 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:15:19 +0300 Subject: [PATCH 14/26] docs: name PostHog's EU region in the working notes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- CLAUDE.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CLAUDE.md b/CLAUDE.md index 2c1b77a..afca028 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -249,7 +249,7 @@ sends. | Channel | Vendor | Default | Toggle | Outbox | |---|---|---|---|---| | Dashboard sync | Fleetify cloud (`fleetify.dev`, WebSocket) | **ON** | Settings → Privacy → "Dashboard sync" | `~/.fleetify/telemetry-outbox.sqlite` | -| Product analytics | PostHog Cloud (US, HTTP `/batch`) | **OFF** | Settings → Privacy → "Product analytics" | `~/.fleetify/posthog-outbox.sqlite` | +| Product analytics | PostHog Cloud (EU, Frankfurt, HTTP `/batch`) | **OFF** | Settings → Privacy → "Product analytics" | `~/.fleetify/posthog-outbox.sqlite` | ### PostHog integration From 884ffc901209d471b0712c681dfc2200a4afc464 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Doruk=20=C3=96zgen?= <140007919+dorukozgen@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:56:22 +0300 Subject: [PATCH 15/26] fix(app): serve the release UI from the binary with a content security policy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A release build now embeds the built UI in the executable, and the embedded backend serves exactly those files, each with a Content-Security-Policy, X-Content-Type-Options and Referrer-Policy. A path that is not one of the files gets an empty 404, and hashed assets may be cached for a year. The bundle no longer ships a dist folder, Tauri's own CSP setting is off, and `tauri build` stops when the UI has not been built. Browsers report what the policy blocks to POST /api/csp-report, which needs no API token; each report is logged on the fleetify.csp target. Signed-off-by: Doruk Özgen <140007919+dorukozgen@users.noreply.github.com> --- Cargo.lock | 16 +- Cargo.toml | 2 +- crates/fleetify-backend/src/access.rs | 23 +- crates/fleetify-backend/src/http.rs | 35 +- crates/fleetify-backend/src/lib.rs | 14 +- crates/fleetify-backend/src/ui.rs | 559 ++++++++++++++++++ crates/fleetify-backend/tests/access.rs | 39 +- crates/fleetify-backend/tests/common/mod.rs | 20 + .../tests/serves_real_dist.rs | 54 -- crates/fleetify-backend/tests/static_dir.rs | 32 - crates/fleetify-backend/tests/ui_assets.rs | 246 ++++++++ src-tauri/Cargo.toml | 3 + src-tauri/build.rs | 26 +- src-tauri/src/lib.rs | 21 +- src-tauri/src/shell/backend_ready.rs | 8 +- src-tauri/src/shell/startup_window.rs | 45 +- src-tauri/src/shell/ui_files.rs | 455 +++++++------- src-tauri/tauri.conf.json | 5 +- 18 files changed, 1198 insertions(+), 405 deletions(-) create mode 100644 crates/fleetify-backend/src/ui.rs delete mode 100644 crates/fleetify-backend/tests/serves_real_dist.rs delete mode 100644 crates/fleetify-backend/tests/static_dir.rs create mode 100644 crates/fleetify-backend/tests/ui_assets.rs diff --git a/Cargo.lock b/Cargo.lock index eb29c2d..170d8c0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1603,6 +1603,7 @@ dependencies = [ "keyring", "notify", "notify-debouncer-mini", + "percent-encoding", "portable-pty 0.9.0", "rand 0.8.6", "reqwest 0.12.28", @@ -2351,12 +2352,6 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "http-range-header" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9171a2ea8a68358193d15dd5d70c1c10a2afc3e7e4c5bc92bc9f025cebd7359c" - [[package]] name = "httparse" version = "1.10.1" @@ -6234,19 +6229,10 @@ checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ "bitflags 2.11.1", "bytes", - "futures-core", "futures-util", "http", "http-body", - "http-body-util", - "http-range-header", - "httpdate", - "mime", - "mime_guess", - "percent-encoding", "pin-project-lite", - "tokio", - "tokio-util", "tower", "tower-layer", "tower-service", diff --git a/Cargo.toml b/Cargo.toml index f7adeea..e4a51e4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,7 +21,7 @@ fleetify-core = { path = "crates/fleetify-core" } fleetify-backend = { path = "crates/fleetify-backend" } tokio = { version = "1", features = ["full"] } axum = { version = "0.8", features = ["ws"] } -tower-http = { version = "0.6", features = ["fs", "trace"] } +tower-http = { version = "0.6", features = ["trace"] } serde = { version = "1", features = ["derive"] } serde_json = "1" thiserror = "2" diff --git a/crates/fleetify-backend/src/access.rs b/crates/fleetify-backend/src/access.rs index ba69ac2..5e38438 100644 --- a/crates/fleetify-backend/src/access.rs +++ b/crates/fleetify-backend/src/access.rs @@ -123,7 +123,9 @@ pub enum Verdict { /// UI); /// - any method under `/api/internal/` (the handlers check the internal /// secret); -/// - `GET /api/mcp/auth/callback`. +/// - `GET /api/mcp/auth/callback`; +/// - `POST /api/csp-report` ([`crate::ui::CSP_REPORT_PATH`]): the browser +/// sends CSP violation reports itself, without the token. /// 4. The token in the header is allowed. /// 5. The token in the query is allowed on a WebSocket upgrade under `/ws/` /// and on `GET /events/status`. @@ -164,6 +166,7 @@ fn needs_no_token(facts: &RequestFacts<'_>) -> bool { || (read && !api) || path.starts_with("/api/internal/") || (*method == Method::GET && path == MCP_AUTH_CALLBACK_PATH) + || (*method == Method::POST && path == crate::ui::CSP_REPORT_PATH) } /// Rule 5 of [`decide`]: where the query token counts. @@ -466,6 +469,24 @@ mod tests { facts(&get, "/api/mcp/auth/callback"), ALLOW, ), + ( + "a CSP violation report", + facts(&post, "/api/csp-report"), + ALLOW, + ), + ( + "a GET of the CSP report path", + facts(&get, "/api/csp-report"), + NO_TOKEN, + ), + ( + "a CSP violation report from a bad host", + RequestFacts { + host: evil, + ..facts(&post, "/api/csp-report") + }, + BAD_HOST, + ), ("a POST to the UI", facts(&post, "/"), NO_TOKEN), ( "a POST to the OAuth callback", diff --git a/crates/fleetify-backend/src/http.rs b/crates/fleetify-backend/src/http.rs index 52774b8..23fc96c 100644 --- a/crates/fleetify-backend/src/http.rs +++ b/crates/fleetify-backend/src/http.rs @@ -1,9 +1,9 @@ -use std::path::PathBuf; - +use axum::extract::DefaultBodyLimit; +use axum::http::{Method, Uri}; use axum::middleware::from_fn_with_state; -use axum::{routing::get, Json, Router}; +use axum::routing::{get, post}; +use axum::{Json, Router}; use serde_json::{json, Value}; -use tower_http::services::ServeDir; use crate::access::{self, AccessPolicy}; use crate::routers::{ @@ -11,17 +11,18 @@ use crate::routers::{ library, marketplace, mcp, messages, plugins, prompt, prompts, providers, routing, runtime, sessions, ssh, user, workflows, workspace, AppState, }; +use crate::ui::{self, UiAssets, UiFiles}; /// The health route. It answers `{"status":"ok","version":…}`, and the /// shell polls it at startup before its warm-up talks to the backend. pub const HEALTH_PATH: &str = "/healthz"; /// Build the axum app. Single origin: `/healthz`, `/api/*` (auth'd), -/// `/events/status` SSE, and the built React assets (when `static_dir`). -/// No CORS: the app's pages come from this origin (or, in dev, through the -/// Vite proxy). [`access::guard`] wraps all of it, the static files and the -/// 404s included. -pub fn app(state: AppState, static_dir: Option, policy: AccessPolicy) -> Router { +/// `/events/status` SSE, the CSP report route, and, with `ui`, the release +/// UI's files as the fallback ([`crate::ui`]). No CORS: the app's pages come +/// from this origin (or, in dev, through the Vite proxy). [`access::guard`] +/// wraps all of it, the UI files and the 404s included. +pub fn app(state: AppState, ui: Option, policy: AccessPolicy) -> Router { let api = sessions::router() .merge(messages::router()) .merge(groups::router()) @@ -53,6 +54,10 @@ pub fn app(state: AppState, static_dir: Option, policy: AccessPolicy) - let routed = Router::new() .route(HEALTH_PATH, get(healthz)) + .route( + ui::CSP_REPORT_PATH, + post(ui::csp_report).layer(DefaultBodyLimit::max(ui::CSP_REPORT_MAX_BYTES)), + ) .nest("/api", api) .nest("/api/internal", internal_api) .merge(events::router()) @@ -60,8 +65,16 @@ pub fn app(state: AppState, static_dir: Option, policy: AccessPolicy) - .merge(browser::ws_router()) .with_state(state); - let routed = match static_dir { - Some(dir) => routed.fallback_service(ServeDir::new(dir)), + // The nested routers have no fallback of their own, so a path under + // `/api` that no route matches ends here too: an empty 404. + let routed = match ui { + Some(assets) => { + let files = UiFiles::new(assets, policy.port); + routed.fallback(move |method: Method, uri: Uri| { + let files = files.clone(); + async move { files.respond(&method, uri.path()) } + }) + } None => routed, }; // Last, so it is the outermost layer: axum applies a layer only to the diff --git a/crates/fleetify-backend/src/lib.rs b/crates/fleetify-backend/src/lib.rs index 14a62ed..937bac0 100644 --- a/crates/fleetify-backend/src/lib.rs +++ b/crates/fleetify-backend/src/lib.rs @@ -20,6 +20,7 @@ pub mod session_manager; pub mod studio; #[cfg(test)] pub mod test_support; +pub mod ui; use std::net::SocketAddr; use std::path::PathBuf; @@ -106,9 +107,10 @@ async fn normalize_legacy_verbatim_project_paths(pool: &sqlx::SqlitePool) { /// What [`serve`] starts with. pub struct ServeOptions { - /// The built React asset directory for single-origin serving (`None` = - /// API only). - pub static_dir: Option, + /// The release UI's files, which the shell embeds in the binary and the + /// backend serves on its own origin ([`ui`]). `None` serves the API + /// only: a debug build loads its UI from the Vite dev server. + pub ui: Option, /// The external routers to hydrate the routing orchestrator with. The /// Tauri shell composes it from `fleet.config.json` + the per-user /// keychain, so the backend stays Tauri-agnostic. @@ -124,7 +126,7 @@ impl ServeOptions { /// master toggle defaults to OFF. pub fn api_only(api_token: access::ApiToken) -> Self { Self { - static_dir: None, + ui: None, routing_setup: services::routing::setup::RoutingSetup::default(), api_token, } @@ -190,7 +192,7 @@ fn api_token_forced() -> bool { /// `FLEETIFY_REQUIRE_API_TOKEN=1`). Both are read once, here. pub async fn serve(addr: SocketAddr, opts: ServeOptions) -> anyhow::Result { let ServeOptions { - static_dir, + ui, routing_setup, api_token, } = opts; @@ -430,7 +432,7 @@ pub async fn serve(addr: SocketAddr, opts: ServeOptions) -> anyhow::Result, + pub mime_type: String, +} + +/// The shell's lookup of an embedded file by request path. +type Lookup = dyn Fn(&str) -> Option + Send + Sync; + +/// The embedded UI files, behind the shell's lookup. +#[derive(Clone)] +pub struct UiAssets(Arc); + +impl UiAssets { + /// `get` answers a request path (see [`UiAssets::get`]). + pub fn new(get: impl Fn(&str) -> Option + Send + Sync + 'static) -> Self { + Self(Arc::new(get)) + } + + /// The file a request path names: `/` means index.html. `None` when the + /// path is not an embedded file. + pub fn get(&self, request_path: &str) -> Option { + (self.0)(request_path) + } +} + +/// Where browsers send CSP violation reports (the policy's `report-uri`). +pub const CSP_REPORT_PATH: &str = "/api/csp-report"; + +/// The largest report body accepted; a larger one gets 413. +pub(crate) const CSP_REPORT_MAX_BYTES: usize = 16 * 1024; + +/// How long the hashed files under `/assets/` may be cached: a year, and +/// they never change under their name. +const IMMUTABLE: &str = "public, max-age=31536000, immutable"; +/// Everything else, index.html first, is revalidated. +const NO_CACHE: &str = "no-cache"; + +/// The origin product analytics sends to, for the policy's `connect-src`: +/// `scheme://host[:port]` of `raw`, the PostHog host the renderer was built +/// with. A missing, empty or unusable value (not an http or https URL) is +/// [`DEFAULT_HOST`], as it is for the renderer (`src/lib/posthog.ts`). +pub fn posthog_origin(raw: Option<&str>) -> String { + raw.and_then(|raw| url::Url::parse(raw).ok()) + .filter(|url| matches!(url.scheme(), "http" | "https")) + .map(|url| url.origin().ascii_serialization()) + .unwrap_or_else(|| DEFAULT_HOST.to_string()) +} + +/// The Content-Security-Policy the UI files are served with, for the +/// backend bound to `port` and analytics sent to `posthog_origin`. +pub fn content_security_policy(port: u16, posthog_origin: &str) -> String { + [ + "default-src 'self'".to_string(), + // 'wasm-unsafe-eval': shiki compiles its Oniguruma WebAssembly. It + // allows WebAssembly only, not eval. + "script-src 'self' 'wasm-unsafe-eval'".to_string(), + // 'unsafe-inline': React's style attributes, and the