trusty_code/serve/http.rs
1//! HTTP JSON-RPC 2.0 transport for `tcode serve --http` (#2053, #2054).
2//!
3//! Why: matches how `trusty-memory` (`web::router` + `run_http_on`) and
4//! `trusty-search` (`service::server::build_router`) stand up their axum
5//! daemons: a pure `axum::Router` builder — testable via `oneshot`, no real
6//! socket — wrapped in the shared guarded middleware stack
7//! (`trusty_common::server::with_guarded_middleware_same_origin_cors`, #6003),
8//! plus a bind+serve entry point that installs the
9//! shared `trusty_common::shutdown_signal()` graceful-shutdown watcher
10//! (SIGTERM + SIGINT), exactly like `trusty-memory`'s `run_http_on`. `POST
11//! /rpc` and `GET /health` dispatch through the SAME [`crate::jsonrpc::Router`]
12//! the STDIO transport (`crate::serve::transport`) uses via
13//! [`Router::dispatch_json`] — there is exactly one implementation of each
14//! method (`ping`, `health`, `session.*`, …), not one per transport.
15//!
16//! #2054 adds `GET /sessions/{id}/events`: an SSE route that is HTTP's real
17//! live-streaming mechanism for `session.attach`. HTTP `POST /rpc` is
18//! fundamentally one request/one response, so `session.attach` over HTTP
19//! acknowledges immediately (replay burst + this endpoint's URL in
20//! `stream_url`) rather than holding the connection open — a browser or CLI
21//! client then opens this endpoint to receive the ring-buffer replay
22//! followed by live events, and simply closing that connection IS "detach"
23//! for HTTP (there is nothing further to call). See
24//! `crate::jsonrpc::ConnectionContext`'s docs and `session::protocol::attach`
25//! for the full STDIO-vs-HTTP rationale. Multi-client attach falls out for
26//! free here: every `GET` gets its own `crate::events::subscribe()`
27//! receiver.
28//!
29//! What: [`build_axum_router`] (pure, unit-testable) and [`run_http`] (binds
30//! a `TcpListener` — port `0` yields an OS-assigned ephemeral port — logs
31//! the bound address to stderr, never stdout, and serves until graceful
32//! shutdown).
33//!
34//! #5439 puts every route behind a credential. `trusty_common::daemon_token`
35//! mints and stores it at `0600`; `trusty_common::server::bearer_auth` is the
36//! router-wide guard, applied here to the FULLY-MERGED router so a route added
37//! later cannot slip past it. [`PUBLIC_HEALTH_PATH`] is the single exemption
38//! and discloses only liveness to an anonymous caller (#6472);
39//! [`SSE_TICKET_PATH`] is how a browser `EventSource`, which cannot send a
40//! header, carries an existing right onto a URL.
41//!
42//! Deferred: batch JSON-RPC requests (a JSON array body) are not supported —
43//! `POST /rpc` accepts a single request object per call, matching what the
44//! ticket asked for ("single-request is fine for now").
45//!
46//! Also deferred, and larger: this whole listener is scheduled for replacement
47//! by a Unix socket fronted by trusty-console (ADR-0032, the #5439 owner
48//! ruling of 2026-08-19), which authenticates by peer credential rather than
49//! by a shared secret. This layer is the hardening that stands until then, not
50//! the end state.
51//!
52//! Test: `http::tests::*` drive [`build_axum_router`] via
53//! `tower::util::ServiceExt::oneshot` (no real socket): `POST /rpc` ping
54//! success, `POST /rpc` malformed JSON -> `-32700`, `GET /health`,
55//! `session.create` + `GET /sessions/{id}/events` SSE replay + live event.
56
57use std::convert::Infallible;
58use std::net::SocketAddr;
59use std::sync::Arc;
60
61use anyhow::{Context, Result};
62use axum::{
63 Extension, Json, Router as AxumRouter,
64 body::Bytes,
65 extract::{Path, State},
66 response::sse::{Event as SseEvent, KeepAlive, Sse},
67 routing::{get, post},
68};
69use futures_util::{Stream, StreamExt, stream};
70use tokio::net::TcpListener;
71use tokio::sync::mpsc;
72use tokio_stream::wrappers::BroadcastStream;
73use tracing::info;
74use trusty_common::server::SelfOrigins;
75use trusty_common::server::bearer_auth::{Authenticated, DaemonAuth, require_bearer};
76use trusty_mcp::Response;
77
78use crate::binding::ProjectBinding;
79use crate::jsonrpc::{ConnectionContext, Router};
80use crate::serve::methods::{health_payload, liveness_payload};
81use crate::serve::rest;
82use crate::session::SessionRegistry;
83use crate::workstreams::SharedWorkstreamStore;
84
85/// The app name whose data directory holds this daemon's credential file.
86///
87/// Why: server (`run_http`) and client (`crate::tui_client`) resolve the token
88/// through the same constant, so they cannot end up reading two files.
89pub const TOKEN_APP_NAME: &str = "trusty-code";
90
91/// The one route that answers an unauthenticated caller (#6472).
92///
93/// Why: trusty-console's gateway polls a daemon for liveness and holds no
94/// credential, and the ecosystem convention (trusty-search, trusty-memory) is
95/// an open `GET /health`. Keeping the ROUTE public while moving its
96/// disclosures behind the credential preserves that poll and still stops an
97/// anonymous caller from reading the daemon's pid, bound project, and version.
98pub const PUBLIC_HEALTH_PATH: &str = "/health";
99
100/// `POST` here (authenticated) to mint a single-use SSE ticket.
101///
102/// Why: `EventSource` cannot send an `Authorization` header, so a browser
103/// client exchanges its credential for a ticket here and puts THAT in the SSE
104/// URL — see `trusty_common::server::bearer_auth`'s module docs.
105pub const SSE_TICKET_PATH: &str = "/auth/sse-ticket";
106
107/// Shared axum state: the JSON-RPC router (for `POST /rpc`), the session
108/// registry (for the SSE route, which reads it directly rather than going
109/// through the router), and the daemon's project binding (for `GET /health`).
110///
111/// Why: every field is an `Arc` so cloning per-request (axum requires
112/// `State` to be `Clone`) is cheap and every route sees the same daemon-wide
113/// instances. `binding` is here rather than resolved per request because a
114/// daemon binds exactly ONE project for its whole life — that immutability
115/// is precisely what makes it worth publishing on `/health` (#4512).
116#[derive(Clone)]
117struct HttpState {
118 router: Arc<Router>,
119 sessions: Arc<SessionRegistry>,
120 binding: Arc<ProjectBinding>,
121 // #5439: the same handle the router-wide guard holds, so `POST
122 // /auth/sse-ticket` mints into the table the guard redeems from.
123 auth: DaemonAuth,
124}
125
126/// Build the pure axum router (no listener bound) exposing `POST /rpc`,
127/// `GET /health`, `GET /sessions/{id}/events`, and (#2983 Slice 2 + Slice 3)
128/// the full `/sessions*` REST resource group.
129///
130/// Why: kept separate from [`run_http`] so unit tests exercise routing and
131/// dispatch via `tower::util::ServiceExt::oneshot` without opening a real
132/// socket, and so the shared guarded middleware stack wraps it identically to
133/// trusty-agents/trusty-memory/trusty-search.
134///
135/// #6003: the stack is
136/// `trusty_common::server::with_guarded_middleware_same_origin_cors`, not the
137/// permissive `with_standard_middleware` this router used to call. Two things
138/// change. `guard_write_origin` runs router-wide and innermost, so a browser
139/// POST/PUT/PATCH/DELETE carrying a foreign `Origin` is `403`ed before any
140/// handler runs — `POST /rpc` (the whole JSON-RPC method surface), `/tasks`,
141/// `/sessions`, `/sessions/{id}/messages`, `/agents`, and the `workstream.*`
142/// write routes. And the CORS policy reflects only same-machine origins
143/// instead of `Any`, so a page on a foreign origin cannot READ
144/// `GET /sessions/{id}/transcript` or either SSE stream either — those are
145/// `GET`, which the method-gated guard deliberately lets through, and they
146/// carry conversation content. Callers that send no `Origin` at all (the
147/// `tcode tui` client, the console reverse proxy, `curl`) are untouched: the
148/// guard passes an absent `Origin` through, and CORS is browser-enforced.
149/// What: `POST /rpc` dispatches the request body through
150/// `Router::dispatch_json` (shared with the STDIO transport); `GET /health`
151/// returns [`health_payload`]; `GET /sessions/{id}/events` streams that
152/// session's ring-buffer replay then live events as SSE; `crate::serve::rest`
153/// merges in the `session.*` REST read routes (`GET /sessions`,
154/// `GET /sessions/{id}`, `.../transcript`, `.../readiness`, `.../goals`,
155/// (issue #3015) `.../budget`),
156/// (Slice 3) the write routes (`POST /sessions`,
157/// `POST /sessions/{id}/messages`, `POST /sessions/{id}/cancel`,
158/// `PUT`/`DELETE /sessions/{id}/goal`), (Slice 4) `POST /tasks`, (Slice 5)
159/// `GET /fs`, (Slice 6) `GET /sessions/{id}/agents`, (Slice 7, issue #3072)
160/// `GET /sessions/{id}/search-audit`, and the full `workstream.*` REST
161/// surface: `POST /workstreams`, `GET /workstreams/{id}`, `GET /workstreams`,
162/// `POST /workstreams/{id}/close` (issue #3295) plus
163/// `POST /workstreams/{id}/activate`/`.../deactivate` (DOC-48 §5.2, issue
164/// #3294) — plus (issue #3297) `GET /workstreams/{id}/events` (the
165/// workstream-level SSE aggregation route, `crate::workstreams::sse::routes`)
166/// — plus (issue #3449) `GET`/`POST /agents`, `DELETE /agents/{name}` and the
167/// `skills` twin (the Foundry GUI's Agents/Skills management tabs,
168/// `rest::agent_catalog`/`rest::skill_catalog`) — none of which collide with
169/// the paths registered directly on this router or with each other.
170/// Test: `http_rpc_ping_returns_pong`,
171/// `http_rpc_malformed_json_returns_parse_error`,
172/// `http_health_matches_jsonrpc_health_payload`,
173/// `http_session_events_sse_streams_replay_then_live_event`,
174/// `http_rest_sessions_route_is_merged_in`,
175/// `http_rest_post_sessions_route_is_merged_in`,
176/// `http_rest_post_tasks_route_is_merged_in`,
177/// `http_rest_get_fs_route_is_merged_in`,
178/// `http_rest_get_session_agents_route_is_merged_in`,
179/// `http_rest_get_session_budget_route_is_merged_in`,
180/// `http_rest_get_session_search_audit_route_is_merged_in`,
181/// `http_rest_get_workstreams_route_is_merged_in` (also pins the
182/// `GET /workstreams/{id}/events` merge),
183/// `http_rest_get_projects_route_is_merged_in`,
184/// `http_rest_get_agent_and_skill_catalog_routes_are_merged_in`;
185/// the #6003 guard arms live in `http_origin_guard_tests`.
186pub fn build_axum_router(
187 router: Arc<Router>,
188 sessions: Arc<SessionRegistry>,
189 workstreams: SharedWorkstreamStore,
190 binding: Arc<ProjectBinding>,
191 // #5439: the daemon's local-client credential. Taken as a parameter (not
192 // read from disk here) so the router stays pure and unit-testable, and so
193 // there is no construction path that yields an unguarded router.
194 auth: DaemonAuth,
195) -> AxumRouter {
196 let state = HttpState {
197 router: router.clone(),
198 sessions,
199 binding,
200 auth: auth.clone(),
201 };
202 let core = AxumRouter::new()
203 .route("/rpc", post(rpc_handler))
204 .route(PUBLIC_HEALTH_PATH, get(health_handler))
205 .route(SSE_TICKET_PATH, post(sse_ticket_handler))
206 .route("/sessions/{id}/events", get(session_events_sse))
207 .with_state(state);
208 let app = core
209 .merge(rest::sessions::routes(router.clone()))
210 .merge(rest::sessions_write::routes(router.clone()))
211 .merge(rest::tasks::routes(router.clone()))
212 .merge(rest::fs::routes(router.clone()))
213 .merge(rest::projects::routes(router.clone()))
214 .merge(rest::agents::routes(router.clone()))
215 .merge(rest::agent_catalog::routes(router.clone()))
216 .merge(rest::skill_catalog::routes(router.clone()))
217 .merge(rest::search_audit::routes(router.clone()))
218 .merge(rest::workstreams::routes(router))
219 .merge(crate::workstreams::sse::routes(workstreams));
220 // #5439: applied to the FULLY-MERGED router with `.layer()`, never
221 // `route_layer` — the latter covers only routes registered before it in the
222 // same chain, which is how #3268 left routes unguarded on the sibling
223 // origin guard. Every route above, and every route a later edit merges in
224 // here, is guarded without anyone remembering to add it.
225 let authed = app.layer(axum::middleware::from_fn_with_state(auth, require_bearer));
226 // #6003: the daemon binds loopback only (`run_http`), so the guard needs no
227 // bind-derived allowlist — `SelfOrigins::default()` trusts loopback and
228 // nothing else. This stack sits OUTSIDE the credential check, so a CORS
229 // preflight is answered without a credential and a foreign-origin write is
230 // still 403ed rather than 401ed.
231 trusty_common::server::with_guarded_middleware_same_origin_cors(authed, SelfOrigins::default())
232}
233
234/// `POST /rpc` — JSON-RPC 2.0 dispatch endpoint.
235///
236/// Why: lets browser clients, curl, and any HTTP-only caller reach the same
237/// method surface the STDIO transport exposes, without learning a REST
238/// vocabulary per method.
239/// What: builds a throwaway [`ConnectionContext`] for this one call (its
240/// `notify` receiver is dropped once this function returns, so any handler
241/// that queued a notification via it — e.g. `session.attach`'s forwarder —
242/// simply stops on its next send; the real HTTP live-streaming path is
243/// `GET /sessions/{id}/events`, not this channel), then dispatches the raw
244/// request body through `Router::dispatch_json` (single request per call —
245/// batch/array bodies are not supported, see module docs). Always returns
246/// HTTP 200; JSON-RPC errors, including malformed JSON (mapped to
247/// `-32700`), are carried in the response envelope's `error` field rather
248/// than the HTTP status.
249/// Test: `http_rpc_ping_returns_pong`, `http_rpc_malformed_json_returns_parse_error`.
250async fn rpc_handler(State(state): State<HttpState>, body: Bytes) -> Json<Response> {
251 let (notify_tx, _notify_rx) = mpsc::unbounded_channel();
252 let ctx = ConnectionContext::new(notify_tx);
253 Json(state.router.dispatch_json(&body, &ctx).await)
254}
255
256/// `GET /health` — liveness for anyone, identity for a credentialed caller.
257///
258/// Why: two callers with different rights meet on this one route. The
259/// ecosystem convention (trusty-search, trusty-memory) is an unauthenticated
260/// `GET /health`, and trusty-console's gateway polls it holding no credential,
261/// so the route must keep answering an anonymous caller. But #6472: the
262/// payload it used to answer with carried the daemon's pid, its bound project
263/// ROOT PATH, and its version — process and filesystem facts an anonymous
264/// local caller has no claim on, and a fingerprint for anything probing
265/// loopback ports. Splitting by credential rather than by route keeps both the
266/// gateway poll and `tcode tui`'s auto-attach working: the TUI reads the same
267/// credential file the daemon writes, so it still gets the `binding` it needs
268/// (#4512) to refuse a daemon bound to a different project.
269///
270/// What: an anonymous caller gets [`liveness_payload`] — `{"status":"ok"}`,
271/// nothing else. A caller the guard marked [`Authenticated`] gets
272/// [`health_payload`], the exact payload the `health` JSON-RPC method returns,
273/// unchanged. Always HTTP 200 either way; a health route must not turn a
274/// missing credential into a failure, or every liveness poller would read a
275/// live daemon as down.
276/// Test: `health_is_public_but_discloses_only_liveness`,
277/// `health_with_a_credential_still_reports_pid_and_binding`,
278/// `http_health_matches_jsonrpc_health_payload`,
279/// `http_health_reports_the_daemons_project_binding`.
280async fn health_handler(
281 State(state): State<HttpState>,
282 authenticated: Option<Extension<Authenticated>>,
283) -> Json<serde_json::Value> {
284 if authenticated.is_some() {
285 return Json(health_payload(&state.binding));
286 }
287 Json(liveness_payload())
288}
289
290/// `POST /auth/sse-ticket` — exchange a bearer credential for a single-use SSE
291/// ticket.
292///
293/// Why: the two SSE routes (`GET /sessions/{id}/events`,
294/// `GET /workstreams/{id}/events`) are opened by browser `EventSource`, which
295/// cannot attach an `Authorization` header. Putting the durable token in the
296/// query string instead would write it into every access log and tracing span;
297/// a ticket that expires in seconds and dies on first use does not carry that
298/// cost. Reaching this route already requires the header, so a ticket is never
299/// a way IN — only a way to carry an existing right onto a URL.
300/// What: takes the path the caller means to open (`?path=`), refuses anything
301/// that is not one of this daemon's two SSE routes, and mints a ticket bound to
302/// that exact path. The route is NOT public, so an anonymous `POST` is `401`ed
303/// by the guard before this function runs.
304///
305/// The binding is what keeps a ticket cheap to leak. Unbound, a ticket read
306/// from a trace log within its TTL bought one arbitrary authenticated request —
307/// `POST /rpc`, the whole method surface, included. Bound, it buys the one
308/// stream its holder already had the credential to open. The route allowlist
309/// lives here rather than in `trusty_common` because it is this daemon's route
310/// table, not a property of the guard.
311/// Test: `http_auth_tests::sse_ticket_requires_a_credential`,
312/// `http_auth_tests::an_sse_ticket_opens_one_stream_then_is_spent`,
313/// `http_auth_tests::a_ticket_cannot_be_minted_for_a_non_sse_path`.
314async fn sse_ticket_handler(
315 State(state): State<HttpState>,
316 axum::extract::Query(params): axum::extract::Query<SseTicketRequest>,
317) -> Result<Json<serde_json::Value>, (axum::http::StatusCode, Json<serde_json::Value>)> {
318 if !path_is_ticketable(¶ms.path) {
319 // No echo of the requested path — this response reaches a browser.
320 return Err((
321 axum::http::StatusCode::BAD_REQUEST,
322 Json(serde_json::json!({"error": "not a ticketable stream"})),
323 ));
324 }
325 Ok(Json(
326 serde_json::json!({ "ticket": state.auth.issue_ticket(¶ms.path) }),
327 ))
328}
329
330/// The `?path=` a ticket request names.
331#[derive(serde::Deserialize)]
332struct SseTicketRequest {
333 path: String,
334}
335
336/// Is `path` one of the two SSE streams a ticket may open?
337///
338/// Why: a ticket is only as narrow as the set of paths it can be minted for. A
339/// handler that minted for whatever it was handed would give back the arbitrary
340/// authenticated request the binding exists to remove.
341/// What: exact shape match on `/sessions/{id}/events` and
342/// `/workstreams/{id}/events` — three segments, the first and last fixed, the
343/// id non-empty and free of `/`. Anything else, `/rpc` included, is refused.
344/// Test: `http_auth_tests::a_ticket_cannot_be_minted_for_a_non_sse_path`.
345fn path_is_ticketable(path: &str) -> bool {
346 let segments: Vec<&str> = path.split('/').collect();
347 // A leading `/` yields an empty first segment: ["", group, id, "events"].
348 matches!(segments.as_slice(),
349 ["", group, id, "events"]
350 if (*group == "sessions" || *group == "workstreams") && !id.is_empty()
351 )
352}
353
354/// `GET /sessions/{id}/events` — Server-Sent Events stream of a session's
355/// ring-buffer replay followed by its live events.
356///
357/// Why: HTTP's real live-streaming mechanism for `session.attach` (see
358/// module docs for why `POST /rpc` itself can't hold the stream open).
359/// Multiple concurrent `GET`s against the same session id each get their
360/// own subscription (multi-client attach, vision spec Axiom 4) — no extra
361/// bookkeeping needed because `crate::events::subscribe()` already hands
362/// out an independent `broadcast::Receiver` per call.
363/// What: 404 with a JSON-RPC error envelope if the session id is unknown
364/// (`SessionRegistry::replay` -> `session_not_found`, spec-mapped HTTP
365/// status per §13.2). Otherwise: an SSE stream that first emits the
366/// ring-buffer replay (oldest-first) then chains the live bus, filtered to
367/// this `session_id`, forever (until the client disconnects — which is
368/// "detach" for HTTP).
369/// Test: `http_session_events_sse_streams_replay_then_live_event`,
370/// `http_session_events_sse_unknown_session_returns_404`.
371async fn session_events_sse(
372 State(state): State<HttpState>,
373 Path(session_id): Path<String>,
374) -> Result<
375 Sse<impl Stream<Item = Result<SseEvent, Infallible>>>,
376 (axum::http::StatusCode, Json<Response>),
377> {
378 let replay = state.sessions.replay(&session_id).map_err(|e| {
379 let body = Response::err(None, e.code, e.message);
380 (axum::http::StatusCode::NOT_FOUND, Json(body))
381 })?;
382
383 let replay_stream = stream::iter(
384 replay
385 .into_iter()
386 .map(|envelope| Ok(sse_event_for(&envelope))),
387 );
388
389 // #8100: an SSE client can answer this session's permission prompt over
390 // `POST /rpc`, so it counts as a prompter. The guard rides the stream's
391 // closure — dropping the response body (the client went away) releases it.
392 let prompter = state.sessions.claim_prompter(&session_id);
393
394 let filter_id = session_id.clone();
395 let live_stream = BroadcastStream::new(crate::events::subscribe()).filter_map(move |item| {
396 let _ = &prompter;
397 let filter_id = filter_id.clone();
398 async move {
399 match item {
400 Ok(envelope) if envelope.session_id == filter_id => {
401 Some(Ok(sse_event_for(&envelope)))
402 }
403 _ => None,
404 }
405 }
406 });
407
408 Ok(Sse::new(replay_stream.chain(live_stream)).keep_alive(KeepAlive::default()))
409}
410
411/// Serialise one `crate::events::SessionEventEnvelope` as an SSE `data:`
412/// frame.
413///
414/// Why: centralises the (practically infallible — the envelope has no
415/// untagged maps or non-string keys) JSON encoding so `session_events_sse`
416/// doesn't repeat the fallback logic at two call sites. Sending the full
417/// envelope (not just the bare `event`) means the HTTP SSE transport carries
418/// exactly the same `session_id`/`seq`/`at`/`kind`/`event` shape the STDIO
419/// `session.event` notification does (#2055 requirement: both transports
420/// carry the full taxonomy with the envelope).
421/// What: `SseEvent::default().json_data(envelope)`, falling back to an empty
422/// JSON object on the (unreachable in practice) serialisation error rather
423/// than `unwrap`ing.
424fn sse_event_for(envelope: &crate::events::SessionEventEnvelope) -> SseEvent {
425 SseEvent::default()
426 .json_data(envelope)
427 .unwrap_or_else(|_| SseEvent::default().data("{}"))
428}
429
430/// Bind a `TcpListener` and serve `POST /rpc` + `GET /health` +
431/// `GET /sessions/{id}/events` until SIGTERM/SIGINT (graceful) or an
432/// internal axum error.
433///
434/// Why: the top-level entry point `crate::serve::run_http` delegates to this
435/// once the router and session registry are assembled.
436/// What: binds `127.0.0.1:port` (`port = 0` lets the OS assign an ephemeral
437/// port), logs the real bound address to stderr — mirroring
438/// `trusty-memory`'s `run_http_on`, and never touching stdout — then serves
439/// with `trusty_common::shutdown_signal()` installed via
440/// `with_graceful_shutdown`: SIGTERM/SIGINT stop new connections and drain
441/// in-flight requests before this function returns (issue #534 convention).
442/// Test: not directly unit-tested (would require a real socket + a real
443/// signal); [`build_axum_router`]'s tests cover the routing/dispatch logic
444/// this serves.
445pub async fn run_http(
446 // #6637: `Arc<Router>`, not `Router` — `crate::serve::uds::run_daemon_on`
447 // builds the router ONCE and serves it over both transports, so a session
448 // created over the socket is the same session an HTTP call sees.
449 router: Arc<Router>,
450 sessions: Arc<SessionRegistry>,
451 workstreams: SharedWorkstreamStore,
452 port: u16,
453 // #4512: published on `GET /health` so an auto-attaching client can tell
454 // WHICH project this daemon serves before it starts driving it.
455 binding: Arc<ProjectBinding>,
456) -> Result<()> {
457 // #5439: establish the credential BEFORE binding. A daemon that cannot
458 // write its token file must refuse to serve rather than serve unguarded,
459 // so this `?` is deliberately fatal — the one place in this function that
460 // is not best-effort.
461 let auth = DaemonAuth::new(
462 trusty_common::daemon_token::ensure_token(TOKEN_APP_NAME)
463 .context("tcode serve --http: establish the daemon credential")?,
464 [PUBLIC_HEALTH_PATH],
465 )
466 .context("tcode serve --http: the stored daemon credential is too weak to guard the API")?;
467
468 let addr = SocketAddr::from(([127, 0, 0, 1], port));
469 let listener = TcpListener::bind(addr)
470 .await
471 .with_context(|| format!("tcode serve --http: bind {addr}"))?;
472 let bound = listener
473 .local_addr()
474 .context("tcode serve --http: read bound local address")?;
475 info!("tcode serve --http: listening on http://{bound}");
476 eprintln!("tcode serve --http: listening on http://{bound}");
477
478 // Issue #3415 (DOC-50 §3.4): write the discovery file a client reads to
479 // find this listener without a hardcoded port. #6637 left
480 // `trusty-code-gui`'s webview as its only reader. Best-effort — a write
481 // failure leaves that client with no pointer, and must never block the
482 // daemon from serving, which every other client reaches over the socket.
483 let discovery_path = crate::serve::discovery::http_addr_path();
484 if let Some(path) = &discovery_path
485 && let Err(e) = crate::serve::discovery::write_http_addr_file(path, &bound)
486 {
487 tracing::warn!(
488 error = %e,
489 path = %path.display(),
490 "tcode serve --http: failed to write daemon discovery file"
491 );
492 }
493
494 let app = build_axum_router(router, sessions, workstreams, binding, auth);
495 axum::serve(listener, app)
496 .with_graceful_shutdown(trusty_common::shutdown_signal())
497 .await
498 .context("tcode serve --http: axum serve failed")?;
499
500 if let Some(path) = &discovery_path {
501 crate::serve::discovery::remove_http_addr_file(path);
502 }
503 info!("tcode serve --http: stopped");
504 Ok(())
505}
506
507#[cfg(test)]
508#[path = "http_tests.rs"]
509mod tests;
510
511#[cfg(test)]
512#[path = "http_origin_guard_tests.rs"]
513mod origin_guard_tests;
514
515#[cfg(test)]
516#[path = "http_auth_tests.rs"]
517mod auth_tests;