diff --git a/.env.example b/.env.example index 26b2738..4dfe2a0 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. @@ -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/.github/workflows/ci.yml b/.github/workflows/ci.yml index 70eddd9..2f738f0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -90,14 +90,14 @@ jobs: # twice. -D warnings makes any lint a failure; the workspace is clean. - name: Clippy (compile + lint) run: cargo clippy --workspace --all-targets -- -D warnings - # Test stays ADVISORY: ~6 tests fail on the Windows runner from - # path-separator (`\` vs `/`) + env assumptions, unrelated to app logic. + # Test stays ADVISORY (continue-on-error) and runs on the Windows runner. # Bounded so a test that hangs (binds a port / spawns a process and waits) # can't wedge the job — continue-on-error keeps a timeout non-blocking. + # --no-fail-fast: a failing test target must not stop the rest from running. - name: Test (advisory) continue-on-error: true timeout-minutes: 12 - run: cargo test --workspace + run: cargo test --workspace --no-fail-fast # Prebuilt cargo-audit binary — `cargo install --locked` compiles it from # source (several minutes) and pushed the job past its timeout. This pulls # a release binary in seconds. Bounded + continue-on-error so a slow or diff --git a/CLAUDE.md b/CLAUDE.md index 094b5c9..afca028 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -249,26 +249,26 @@ 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 - **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/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 432033a..1b9c7fb 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 = ["trace"] } serde = { version = "1", features = ["derive"] } serde_json = "1" thiserror = "2" @@ -65,14 +65,15 @@ incremental = true # unaffected (it strips symbols). debug = "line-tables-only" -# Vendored fork of tauri-runtime-wry 2.11.2 with two changes, documented in +# Vendored fork of tauri-runtime-wry 2.11.2 with three changes, documented in # vendor/tauri-runtime-wry/FLEETIFY_PATCH.md: the Linux embedded browser # (right-panel webview) can be positioned instead of stacking full-width at the -# bottom of the window (upstream bug: tauri-apps/tauri #13071 / #10420), and on +# bottom of the window (upstream bug: tauri-apps/tauri #13071 / #10420), on # WebKitGTK a frame inside the app can't use the app page's IPC permissions -# through postMessage. Everything else is a verbatim copy of the published -# crate. Remove this patch (and the vendor/ dir) once upstream fixes both. The -# version must stay equal to the tauri-runtime-wry that `tauri` pulls in, or -# Cargo will ignore the patch. +# through postMessage, and the embedded browser gets no Tauri IPC at all. +# Everything else is a verbatim copy of the published crate. Remove this patch +# (and the vendor/ dir) once upstream covers all three. The version must stay +# equal to the tauri-runtime-wry that `tauri` pulls in, or Cargo will ignore +# the patch. [patch.crates-io] tauri-runtime-wry = { path = "vendor/tauri-runtime-wry" } 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/crates/fleetify-backend/src/access.rs b/crates/fleetify-backend/src/access.rs new file mode 100644 index 0000000..5e38438 --- /dev/null +++ b/crates/fleetify-backend/src/access.rs @@ -0,0 +1,827 @@ +//! 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. [`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: +//! +//! - 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, HeaderMap, Method, 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"; + +/// 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); + +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 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`; +/// - `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`. +/// 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) + || (*method == Method::POST && path == crate::ui::CSP_REPORT_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 +/// 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: 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 { + 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), + } +} + +/// 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 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 { + 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 axum::body::Body; + use axum::http::{Method, Request}; + use axum::middleware::from_fn_with_state; + use axum::routing::get; + use axum::Router; + use tower::ServiceExt; + + use super::*; + use crate::test_support::LogCapture; + + #[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"")); + } + + #[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 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", + 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(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) + .await + .unwrap(); + (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 { + req = req.header("host", *host); + } + 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()); + 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 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(); + 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"); + } + + #[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/agentic/executor.rs b/crates/fleetify-backend/src/agentic/executor.rs index cf36929..69d3dd8 100644 --- a/crates/fleetify-backend/src/agentic/executor.rs +++ b/crates/fleetify-backend/src/agentic/executor.rs @@ -431,6 +431,10 @@ async fn exec_run_command(input: &Value, ws: &Workspace) -> Result { // Kill the process group on drop (set via tokio's kill_on_drop) // so a timed-out child doesn't linger after we move on. .kill_on_drop(true); + // cmd.exe truncates an inherited PATH over 8191 chars, after which not + // even System32 programs are found; the dev launch chain grows PATH past + // that. Give the shell the user's canonical PATH. No-op off Windows. + crate::bridges::apply_clean_path(&mut cmd); let child = cmd.spawn().map_err(|e| anyhow!("spawn failed: {e}"))?; let out = tokio::time::timeout(Duration::from_secs(timeout_secs), child.wait_with_output()) @@ -730,8 +734,10 @@ mod tests { let ws = Workspace::new(dir.path()).unwrap(); let cmd = if cfg!(windows) { // `ping -n N` waits N-1 seconds; 30 pings = 29s wall. Plenty - // to exceed our 1s timeout. - "ping -n 30 127.0.0.1 >NUL" + // to exceed our 1s timeout. Named by full path: cmd.exe + // truncates a long PATH (the next test covers that), and the + // full path keeps this test about the timeout alone. + r"%SystemRoot%\System32\ping.exe -n 30 127.0.0.1 >NUL" } else { "sleep 30" }; @@ -748,6 +754,60 @@ mod tests { assert!(r.content.contains("timed out")); } + #[cfg(windows)] + #[allow(clippy::await_holding_lock)] + #[tokio::test] + async fn run_command_finds_programs_when_inherited_path_is_too_long() { + // cmd.exe truncates a PATH over 8191 chars, and then even System32 + // programs are "not recognized". The dev launch chain grows PATH + // past that, so run_command must not hand the shell the inherited one. + // + // PATH is process-wide: hold the env lock across the run, and put + // the original back on the way out, even if an assertion fails. + let _g = crate::test_support::home_lock() + .lock() + .unwrap_or_else(|p| p.into_inner()); + struct RestorePath(Option); + impl Drop for RestorePath { + fn drop(&mut self) { + match self.0.take() { + Some(path) => std::env::set_var("PATH", path), + None => std::env::remove_var("PATH"), + } + } + } + let original = std::env::var_os("PATH"); + let _restore = RestorePath(original.clone()); + + // Junk entries alone go past the limit; the real PATH follows them. + let mut long = std::ffi::OsString::new(); + let mut i = 0; + while long.len() <= 8191 { + long.push(format!(r"C:\fleetify-test-path-padding\{i:04};")); + i += 1; + } + if let Some(path) = &original { + long.push(path); + } + std::env::set_var("PATH", &long); + + let dir = tempdir().unwrap(); + let ws = Workspace::new(dir.path()).unwrap(); + let r = ex( + &call("run_command", serde_json::json!({"command": "where cmd"})), + &ws, + Mode::Autonomous, + ) + .await; + assert!(!r.is_error, "got: {}", r.content); + assert!(r.content.contains("exit code: 0"), "got: {}", r.content); + assert!( + r.content.to_ascii_lowercase().contains("cmd.exe"), + "got: {}", + r.content + ); + } + #[tokio::test] async fn unknown_tool_returns_clear_error() { let dir = tempdir().unwrap(); diff --git a/crates/fleetify-backend/src/http.rs b/crates/fleetify-backend/src/http.rs index 7eef813..23fc96c 100644 --- a/crates/fleetify-backend/src/http.rs +++ b/crates/fleetify-backend/src/http.rs @@ -1,44 +1,28 @@ -use std::path::PathBuf; - -use axum::http::{HeaderValue, Method}; -use axum::{routing::get, Json, Router}; +use axum::extract::DefaultBodyLimit; +use axum::http::{Method, Uri}; +use axum::middleware::from_fn_with_state; +use axum::routing::{get, post}; +use axum::{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, 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`). -/// 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()); - +/// `/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()) @@ -63,25 +47,39 @@ pub fn app(state: AppState, static_dir: Option) -> Router { .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() .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()) .merge(chat::router()) .merge(browser::ws_router()) - .with_state(state) - .layer(cors); + .with_state(state); - 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 + // 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..937bac0 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; @@ -19,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; @@ -103,20 +105,32 @@ 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 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. + 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 { + ui: None, + routing_setup: services::routing::setup::RoutingSetup::default(), + api_token, + } + } } /// Whether this instance should isolate its sessions DB under FLEETIFY_HOME: @@ -163,15 +177,25 @@ 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 { +/// `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, 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 { + ui, + 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 +417,22 @@ 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 token_required = access::token_required( + !cfg!(debug_assertions), + auth::is_no_auth(), + api_token_forced(), + ); + tracing::info!( + target: "fleet-backend", + api_token_required = token_required, + "access policy" + ); + let policy = access::AccessPolicy { + port: local_addr.port(), + token: api_token, + token_required, + }; + let router = app(state, ui, policy); tokio::spawn(async move { let server = axum::serve(listener, router).with_graceful_shutdown(async { let _ = shutdown_rx.await; @@ -582,3 +621,19 @@ mod dotenv_tests { assert!(should_load_dotenv(false)); } } + +#[cfg(test)] +mod api_token_tests { + use super::api_token_forced; + + #[test] + fn only_require_api_token_1_forces_the_token_and_only_in_debug_builds() { + // No other lib test reads this variable (none calls serve()). + std::env::set_var("FLEETIFY_REQUIRE_API_TOKEN", "1"); + assert_eq!(api_token_forced(), cfg!(debug_assertions)); + std::env::set_var("FLEETIFY_REQUIRE_API_TOKEN", "true"); + assert!(!api_token_forced()); + std::env::remove_var("FLEETIFY_REQUIRE_API_TOKEN"); + assert!(!api_token_forced()); + } +} 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..cc42717 100644 --- a/crates/fleetify-backend/src/routers/internal.rs +++ b/crates/fleetify-backend/src/routers/internal.rs @@ -6,9 +6,10 @@ //! `X-Fleet-Internal: ` 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. @@ -28,6 +29,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 +747,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 +1113,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/routers/ssh.rs b/crates/fleetify-backend/src/routers/ssh.rs index 8141b8d..42c6d65 100644 --- a/crates/fleetify-backend/src/routers/ssh.rs +++ b/crates/fleetify-backend/src/routers/ssh.rs @@ -4,7 +4,7 @@ //! StrictHostKeyChecking=accept-new so first contact registers a key //! without an interactive prompt. -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use axum::routing::{get, post}; use axum::{Json, Router}; @@ -86,7 +86,9 @@ fn home() -> PathBuf { ) } -fn build_ssh_args(t: &SshTarget) -> Vec { +/// `home` is the directory a leading `~` in the identity file stands for; +/// callers pass `home()`. +fn build_ssh_args(t: &SshTarget, home: &Path) -> Vec { let mut args = vec![ "-o".into(), "BatchMode=yes".into(), @@ -101,9 +103,9 @@ fn build_ssh_args(t: &SshTarget) -> Vec { // Expand ~ so the user can paste "~/.ssh/id_ed25519" without // the shell interpreting it. let expanded = if let Some(rest) = idf.strip_prefix("~/") { - home().join(rest).to_string_lossy().into_owned() + home.join(rest).to_string_lossy().into_owned() } else if idf == "~" { - home().to_string_lossy().into_owned() + home.to_string_lossy().into_owned() } else { idf.to_string() }; @@ -246,7 +248,7 @@ fn parse_ssh_config(text: &str) -> Vec { async fn test_target(Json(t): Json) -> Result, ApiError> { validate(&t)?; - let mut cmd = build_ssh_args(&t); + let mut cmd = build_ssh_args(&t, &home()); cmd.push("echo".into()); cmd.push("ok".into()); let (rc, out, err) = run_ssh_cmd(&cmd, 8).await; @@ -284,7 +286,7 @@ async fn list_dir(Json(req): Json) -> Result, ApiError> printf '\\n'; \ done" ); - let mut cmd = build_ssh_args(&req.target); + let mut cmd = build_ssh_args(&req.target, &home()); cmd.push("sh".into()); cmd.push("-c".into()); cmd.push(script); @@ -414,18 +416,34 @@ mod tests { #[test] fn build_ssh_args_expands_tilde_in_identity_file() { - let t = SshTarget { - host: "h".into(), - user: "u".into(), - port: 22, - identity_file: Some("~/.ssh/id_ed25519".into()), + // The home is passed in, not read from USERPROFILE / HOME, which + // other tests point at temp dirs. It has a `~` of its own, like a + // Windows 8.3 short name (the CI runner's is `RUNNER~1`): only a + // leading `~` stands for the home. + let home = if cfg!(windows) { + PathBuf::from(r"C:\Users\RUNNER~1") + } else { + PathBuf::from("/home/RUNNER~1") + }; + let identity_arg = |identity_file: &str| { + let t = SshTarget { + host: "h".into(), + user: "u".into(), + port: 22, + identity_file: Some(identity_file.into()), + }; + let args = build_ssh_args(&t, &home); + let idx = args.iter().position(|a| a == "-i").unwrap(); + args[idx + 1].clone() }; - let args = build_ssh_args(&t); // -i argument is the home-expanded path, not the literal "~". - let idx = args.iter().position(|a| a == "-i").unwrap(); - let path = &args[idx + 1]; - assert!(path.contains(".ssh")); - assert!(!path.contains('~')); + assert_eq!( + identity_arg("~/.ssh/id_ed25519"), + home.join(".ssh/id_ed25519").to_string_lossy() + ); + assert_eq!(identity_arg("~"), home.to_string_lossy()); + // A `~` anywhere else is part of the path and stays as written. + assert_eq!(identity_arg("keys/RUNNER~1/id"), "keys/RUNNER~1/id"); } #[test] 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/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..07ee5fd 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. @@ -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/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/src/ui.rs b/crates/fleetify-backend/src/ui.rs new file mode 100644 index 0000000..ddb64b8 --- /dev/null +++ b/crates/fleetify-backend/src/ui.rs @@ -0,0 +1,559 @@ +//! The release UI: the built renderer files the shell embeds in the binary, +//! served by the backend on its own origin under a Content-Security-Policy +//! it computes itself. +//! +//! The shell hands [`crate::serve`] a [`UiAssets`] (`ServeOptions::ui`) +//! that answers exactly the embedded files (`shell::ui_files`). `http::app` +//! makes it the router's fallback: +//! +//! - `GET` or `HEAD` of `/` is index.html, and of any other embedded file's +//! path that file. Anything else is an empty 404: no index.html in place +//! of a missing file, under `/api/` or anywhere else. Other methods get +//! 405. +//! - Every answer carries the policy ([`content_security_policy`]), +//! `X-Content-Type-Options: nosniff` and `Referrer-Policy: no-referrer`. +//! The hashed files under `/assets/` may be cached for a year; everything +//! else, index.html first, is revalidated. +//! +//! Browsers send what the policy blocks to [`CSP_REPORT_PATH`], which needs +//! no API token (`access::decide`), and each report becomes one warning on +//! the `fleetify.csp` target. +//! +//! Tauri's own policy (`app.security.csp`) is off: it applies only to the +//! `tauri://` protocol, which the app doesn't load, and it would rewrite +//! index.html with per-request nonces and hashes the page doesn't need, as +//! it has no inline scripts. + +use std::sync::Arc; + +use axum::body::Bytes; +use axum::http::{header, HeaderValue, Method, StatusCode}; +use axum::response::{IntoResponse, Response}; + +use crate::services::telemetry::posthog::DEFAULT_HOST; + +/// One embedded UI file. +pub struct UiAsset { + pub bytes: Vec, + 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