trusty_code/serve/rest/fs.rs
1//! `GET /fs` REST route over the `fs.list_dir` JSON-RPC method (#2983
2//! Slice 5).
3//!
4//! Why: the daemon-side folder picker (`crate::fs_browse::protocol` — screen
5//! 7a) is the other half of the local-development surface a REST-only
6//! client needs alongside `session.*`/`task.*`. As with every route in this
7//! gateway, the handler stays thin — extract the query params, call
8//! `super::respond` — because the actual behaviour (path expansion/
9//! canonicalization, the `NotFound`/`PermissionDenied`/`NotADirectory`/
10//! `NoHome`/`Io` error taxonomy) already lives in
11//! `crate::fs_browse::protocol::list_dir`; duplicating it here would fork
12//! the two surfaces (see `super` module docs). No path-scoping/validation
13//! logic belongs in this handler either — `fs.list_dir` intentionally
14//! carries none (`crate::fs_browse` module docs: tcode is a local app run by
15//! the operator, not a multi-tenant service), and this route must not
16//! second-guess that decision.
17//! What: [`routes`] builds a standalone `axum::Router<()>` (its own `FsState`
18//! carrying just the `Arc<Router>`, `with_state`-erased before return,
19//! mirroring `super::sessions::SessionsState`) mapping
20//! `GET /fs?path=..&include_hidden=..` -> `fs.list_dir`. The simpler
21//! `GET /fs` shape (rather than `GET /fs/list`) was chosen because no spec in
22//! this repo mandates a `/list` suffix: DOC-39 §5.0 ("Today's surface")
23//! explicitly says "there is no REST resource surface", and its §5.8
24//! (`project.list_dir`, predating the #2983 REST gateway) proposes that
25//! method as "a new method on the existing `POST /rpc` route — no new HTTP
26//! route" rather than any REST shape at all.
27//! `crate::serve::http::build_axum_router` merges this into the daemon's main
28//! router alongside `POST /rpc`, `GET /health`, `GET /sessions/{id}/events`,
29//! and the other REST resource groups — `/fs` collides with none of them.
30//! Test: `tests::*`.
31
32use std::sync::Arc;
33
34use axum::Router as AxumRouter;
35use axum::extract::{Query, State};
36use axum::routing::get;
37use serde::Deserialize;
38use serde_json::json;
39
40use crate::jsonrpc::Router;
41
42use super::{RestResult, respond};
43
44/// Shared axum state for the route in this module: just the JSON-RPC
45/// router, mirroring `super::sessions::SessionsState` — the handler goes
46/// through [`super::respond`] rather than touching the filesystem directly.
47#[derive(Clone)]
48struct FsState {
49 router: Arc<Router>,
50}
51
52/// Build the `GET /fs` route group.
53///
54/// Why: kept separate from `crate::serve::http::build_axum_router` so this
55/// resource group is unit-testable via `tower::util::ServiceExt::oneshot` on
56/// its own, exactly like every other `rest::*` group.
57/// What: one `GET` route, `FsState { router }`, `with_state`-erased to
58/// `axum::Router<()>` so the caller can `.merge()` it alongside the other
59/// resource groups into the daemon's main router.
60/// Test: `tests::list_dir_returns_200_with_entries`.
61pub fn routes(router: Arc<Router>) -> AxumRouter {
62 AxumRouter::new()
63 .route("/fs", get(list_dir))
64 .with_state(FsState { router })
65}
66
67/// Query params for `GET /fs`, shaped like `fs_browse::protocol`'s private
68/// `ListDirParams` — forwarded verbatim into the RPC `params` `Value`, so
69/// `fs.list_dir`'s own defaulting (`path` -> `~`, `include_hidden` -> `false`)
70/// applies identically either way.
71#[derive(Deserialize)]
72struct ListDirQuery {
73 #[serde(default)]
74 path: Option<String>,
75 #[serde(default)]
76 include_hidden: Option<bool>,
77}
78
79/// `GET /fs?path=..&include_hidden=..` -> `fs.list_dir`.
80///
81/// Why: the REST entry point for the daemon-side folder picker.
82/// What: `200` with the `DirListing` JSON on success; error mapping relies
83/// entirely on `super::rpc_error_to_status`, which already distinguishes
84/// `fs.list_dir`'s four caller-actionable causes: an unknown `path` ->
85/// `-32002 not_found` -> `404`; a `path` that exists but is not a directory
86/// (or an unresolvable `~`) -> `-32003 invalid_argument` -> `400`; an OS
87/// permission refusal -> `-32001 permission_denied` -> `403`; any other OS
88/// fault -> `-32603 internal` -> `500` — four distinct statuses for four
89/// distinct causes, with no new mapping needed in this route (see
90/// `fs_browse::protocol::to_rpc_error`'s docs for the source taxonomy).
91/// Test: `tests::list_dir_returns_200_with_entries`,
92/// `tests::list_dir_nonexistent_path_returns_404`,
93/// `tests::list_dir_file_path_returns_400_distinct_from_404`.
94async fn list_dir(State(state): State<FsState>, Query(q): Query<ListDirQuery>) -> RestResult {
95 respond(
96 &state.router,
97 "fs.list_dir",
98 json!({"path": q.path, "include_hidden": q.include_hidden}),
99 )
100 .await
101}
102
103#[cfg(test)]
104mod tests {
105 use super::*;
106 use axum::body::{Body, to_bytes};
107 use axum::http::{Request, StatusCode};
108 use serde_json::Value;
109 use tower::util::ServiceExt;
110
111 fn app() -> AxumRouter {
112 let mut router = Router::new();
113 crate::fs_browse::protocol::register(&mut router);
114 routes(Arc::new(router))
115 }
116
117 async fn body_json(response: axum::response::Response) -> Value {
118 let bytes = to_bytes(response.into_body(), 1024 * 1024).await.unwrap();
119 serde_json::from_slice(&bytes).unwrap()
120 }
121
122 async fn get(app: &AxumRouter, uri: &str) -> axum::response::Response {
123 app.clone()
124 .oneshot(
125 Request::builder()
126 .method("GET")
127 .uri(uri)
128 .body(Body::empty())
129 .unwrap(),
130 )
131 .await
132 .unwrap()
133 }
134
135 /// A real directory must return `200` with its entries.
136 #[tokio::test]
137 async fn list_dir_returns_200_with_entries() {
138 let tmp = tempfile::tempdir().expect("tempdir");
139 std::fs::create_dir(tmp.path().join("alpha")).expect("mkdir");
140
141 let resp = get(&app(), &format!("/fs?path={}", tmp.path().display())).await;
142 assert_eq!(resp.status(), StatusCode::OK);
143 let v = body_json(resp).await;
144 assert_eq!(v["entries"][0]["name"], "alpha");
145 }
146
147 /// A path that does not exist must be a real `404` with a `not_found`
148 /// envelope.
149 #[tokio::test]
150 async fn list_dir_nonexistent_path_returns_404() {
151 let tmp = tempfile::tempdir().expect("tempdir");
152 let missing = tmp.path().join("no-such-dir");
153
154 let resp = get(&app(), &format!("/fs?path={}", missing.display())).await;
155 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
156 let v = body_json(resp).await;
157 assert_eq!(v["error"]["code"], -32002);
158 }
159
160 /// A path that exists but is a FILE must be a `400`, distinct from the
161 /// `404` above — proving the two RPC error codes
162 /// (`not_found`/`invalid_argument`) reach the client as two distinct HTTP
163 /// statuses, not a single generic "bad path" response.
164 #[tokio::test]
165 async fn list_dir_file_path_returns_400_distinct_from_404() {
166 let tmp = tempfile::tempdir().expect("tempdir");
167 let file = tmp.path().join("a.txt");
168 std::fs::write(&file, "x").expect("write");
169
170 let resp = get(&app(), &format!("/fs?path={}", file.display())).await;
171 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
172 assert_ne!(resp.status(), StatusCode::NOT_FOUND);
173 let v = body_json(resp).await;
174 assert_eq!(v["error"]["code"], -32003);
175 }
176}